1.导入py文件自己
x = 1 y = 2 import main as ojx #直接导入自己文件名 print(‘==>‘, hasattr(ojx, ‘x‘))
x = 1 y = 2 import sys obj1 = sys.modules[__name__] print(‘==>‘, hasattr(obj1, ‘x‘))
2.isinstance(obj,cls)-是否是cls(或继承自cls的类)实例出来的对象
3.issubclass(sub,super)-是否是子类
4.__getattribute__
前面学过getattr(obj,item)获取属性,
__getattr__属性不存在的时候调用,
现在又来个__getattribute__,又是干啥的呢。
class Test: def __init__(self, name): self.name = name def __getattr__(self, item): print(‘from __getattr__‘) def __getattribute__(self, item): print(‘from __getattribute‘) test1 = Test(‘苍老师‘) test1.name test1.age
调用存在的name属性和不存在的age属性,都会调用__getattribute__。没有调用__getattr__,什么时候调用呢?
class Test: def __init__(self, name): self.name = name def __getattr__(self, item): #接住AttributeError异常 print(‘from __getattr__‘) def __getattribute__(self, item): print(‘from __getattribute‘) raise AttributeError(‘小弟,接着异常‘) #抛出异常 test1 = Test(‘苍老师‘) test1.name test1.age
执行的流程:
抛出异常后面要学,这里不必深究。
python基础-面向对象(十三)面向对象进阶(一):导入py文件自己,isinstance(obj,cls),issubclass(sub,super),__getattribute__
原文:https://www.cnblogs.com/liaoyifu/p/14132574.html