标签:turned print hat 操作 nat 修改 检测 init let
反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省),python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)
#1、判断object中有没有一个name字符串对应的方法或属性 hasattr(object,name) #2、获取object中有没有一个name字符串对应的方法或属性 def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, ‘y‘) is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn‘t exist; without it, an exception is raised in that case. """ pass #3、设置object中有没有一个name字符串对应的方法或属性 def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, ‘y‘, v) is equivalent to ``x.y = v‘‘ """ pass #4、删除object中有没有一个name字符串对应的方法或属性 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 Foo: x=1 def __init__(self,name): self.name=name def f1(self): print(‘from f1‘) # print(Foo.x) #Foo.__dict__[‘x‘] f=Foo(‘egon‘) # 判断 #hasattr print(hasattr(f,‘name‘)) #f.name print(hasattr(f,‘f1‘)) #f.f1 print(hasattr(f,‘x‘)) #f.x # 设置 #setattr setattr(f,‘age‘,18)#f.age=18 # 获得 #getattr print(getattr(f,‘name‘))#f.name print(getattr(f,‘abc‘,None))#f.abc print(getattr(f,‘name‘,None))#f.abc func=getattr(f,‘f1‘)#f.f1 print(func) func() # #delattr 删除 delattr(f,‘name‘)# del f.name print(f.__dict__)
标签:turned print hat 操作 nat 修改 检测 init let
原文地址:http://www.cnblogs.com/liuxiaowei/p/7415086.html