class Foo:
f = '类的静态字段'
def __init__(self, name):
self.name = name
self.common = '类的普通字段'
def say_hi(self):
print('hi, %s' % self.name)
obj = Foo('jack')
# 判断是否含有某属性
print(hasattr(Foo, 'f'))
print(hasattr(obj, 'name'))
print(hasattr(obj, 'say_hi'))
# 获取属性
print(getattr(Foo, 'f'))
print(getattr(obj, 'name'))
getattr(obj, 'say_hi')()
print(getattr(obj, 'empty', "Does't exist."))
关于模块
import sys
if hasattr(sys.modules[__name__], 'Foo'):
getattr(getattr(sys.modules[__name__], 'Foo')('jack'), 'say_hi')()
setattr(obj, 'name', 'other')
print(getattr(obj, 'name'))