def eat():
print("I am eating...")
class Persobject):
def __init__(self,name):
self.e = name
def run(self):
print("I can run...")
@staticmethod
def static_test(self):
print("this is static test...")
p = Person("john")
assert hasattr(p,"run") #hasattr(p,'run'):用来判断一个对象p里是否有对应的字符串(如“run”)的方法
fun = getattr(p,"run")#getattr(p,'run'):根据字符串(如“run”)去获取p对象里对应的方法的内存地址(本例中run方法的内存地址)
fun()
out------------------------------------
I can run...
setattr(p,"age",22) #添加了age属性,值为22
print(p.age)
delattr(p,"age")
out-----------------------------------------
22
setattr(p,"have",eat) #就是给类添加eat方法,p.have = eat
func = getattr(p,"have")
func()
out ----------------------------
I am eating...
如果添加的eat方法中实例参数self,那么写法就有些不同了
def eat1(self):
print("this is eat1...")
setattr(p,"has",eat1)
func = getattr(p,"has")
func(p)
out-----------------------------------
this is eat1...
这就像如果你在类中添加了静态方法,且里面有实例参数self,那么也是这种写法
p.static_test(p)
out------------------------------------
this is static test...