getattr 对类使用

class Foo(object):

staticField = "old boy"

def __init__(self):
self.name = 'wupeiqi'

def func(self):
return 'func'

@staticmethod
def bar():
return 'bar'
f=Foo()
print(getattr(Foo, 'staticField'))
my_fun=getattr(f, 'func')
my_bar=getattr(Foo, 'bar')
error_fun=getattr(Foo,"func")


print(my_fun()) #实例化可以打印
print(my_bar()) # 不用传self可以打印
print(error_fun()) #TypeError: func() missing 1 required positional argument: 'self'
原文地址:https://www.cnblogs.com/david-python/p/13912751.html