isinstance(obj,cls)检查是否obj是否是类 cls 的对象
issubclass(sub, super)检查sub类是否是 super 类的派生类
class Foo: def __init__(self,x): self.x = x class SubFoo(Foo): def __init__(self): pass f1 = Foo(2) print(isinstance(f1,Foo)) # True print(issubclass(SubFoo,Foo)) # True
__getattribute__
当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError
class Foo: def __init__(self,x): self.x=x def __getattribute__(self, item): print('不管是否存在,我都会执行') f1=Foo(10) f1.x f1.xxxxxx
class Foo: def __init__(self,x): self.x = x def __getattr__(self, item): print("执行__getattr...") #return self.__dict__[item] def __getattribute__(self, item): print("不管是否存在,都会执行__getattribute...") raise AttributeError("%s not exit" %(item)) class SubFoo(Foo): def __init__(self): pass f1 = Foo(2) f1.x f1.y ''' 不管是否存在,都会执行__getattribute... 执行__getattr... 不管是否存在,都会执行__getattribute... 执行__getattr... '''
item
class Foo: def __init__(self,name): self.Name = name def __getitem__(self, item): print('__getitem__') return self.__dict__[item] def __setitem__(self, key, value): print('__setitem__') self.__dict__[key] = value def __delitem__(self, key): print('__delitem__') self.__dict__.pop(key) f = Foo('lisi') print(f.__dict__) # {'Name': 'lisi'} f['age'] = 18 # __setitem__ print(f.__dict__) # {'Name': 'lisi', 'age': 18} print(f['Name']) # __getitem__ lisi del f['age'] # __delitem__
__str__,__repr__,__format__
改变对象的字符串显示__str__,__repr__
自定制格式化字符串__format__
class School: def __init__(self,name): self.name = name def __str__(self): return self.name scl = School("CPU") print(scl) # CPU