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'
posted @ 2020-11-02 08:59  待喂的z  阅读(86)  评论(0编辑  收藏  举报