面向对象进阶
isinstance(obj,cls)检查obj是否是类cls的对象
class Foo(object): passobj = Foo()print(isinstance(obj,Foo))
issubclass(sub,super)检查sub类是否是super类的派生类
class Foo(object): passclass Bar(Foo): passprint(issubclass(Bar,Foo))
反射
1、什么是反射??
主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。
2、python中面向对象的反射:通过字符串的形式操作对象的属性。python中一切皆对象,都可以使用反射。
四个可以实现反射的函数--适用与类和对象
hasattr(object,name)##判断object中有没有一个name字符串对应的方法或属性,返回布尔值class test(): name = 'egon' def run(self): return 'helloworld't = test()print(hasattr(t,'run'))print(hasattr(t,'helloworld'))-----------------------------getattr(object,name) #获取对象object的属性或者方法class teat(): name = 'egon' def run(self): return 'helloworld't = teat()getattr(t,'name') #获取name属性。存在就打印出来getattr(t,'run') #获取run方法,存在就打印方法的内存地址,加括号可以直接运行getattr(t,'age') #获取一个不存在的属性。报错getattr(t,'age','18') # 若属性不存在,返回一个默认值------------------------------# setattr(object,name,value)#给对象的属性赋值,如属性不存在,就先创建再赋值class test(): name = 'xiaohua' def run(self): return 'helloword't = test()hasattr(t,'age') #判断属性是否存在setattr(t,'age','18') #为属性赋值,没有返回值hasattr(t,'age') #属性存在来-----------------------------------------------def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """ pass
四种函数的实例
class BlackMedium: feature = 'Ugly' def __init__(self,name,addr): self.name = name self.addr = addr def sell_house(self): print('%s 黑中介卖房子啦,傻逼才买呢,但是谁能证明自己不傻逼' %self.name) def rent_house(self): print('%s 黑中介租房子啦,傻逼才租呢' %self.name)b1 = BlackMedium('坐而论道','起而行之')#监测是否含有某属性print(hasattr(b1,'name'))print(hasattr(b1,'sell_house'))#获取属性n = getattr(b1,'name')print(n)func = getattr(b1,'rent_house')func()print(getattr(b1,'aaaaa','不存在啊'))#设置属性setattr(b1,'sd',True)setattr(b1,'show_name',lambda self:self.name+'sb')print(b1.__dict__)print(b1.show_name(b1))#删除属性delattr(b1,'addr')delattr(b1,'show_name')delattr(b1,'show_nameall') #不存在,则报错
类也是对象
class Foo(object): staticField = 'old boy' def __init__(self): self.name = 'xiaoming' def func(self): return 'func' @staticmethod def bar(): return 'bar'print(getattr(Foo,'staticField'))print(getattr(Foo,'func'))print(getattr(Foo,'bar'))
反射当前模块成员
import sysdef s1(): print('s1')def s2(): print('s2')this_module = sys.modules[__name__]print(hasattr(this_module,'s1'))print(getattr(this_module,'s2'))