class Foo(object): def __init__(self): self.name = ‘wupeiqi‘ # self.age = age def func(self): print("func is running.") return ‘func‘ obj = Foo() # #### 检查是否含有成员 #### print(hasattr(obj, ‘name‘)) print(hasattr(obj, ‘func‘)) # # #### 获取成员 #### print(getattr(obj, ‘name‘)) print(getattr(obj, ‘func‘)) getattr(obj, ‘func‘)() # # # #### 设置成员 #### 相当于增加成员。 print(setattr(obj, ‘age‘, 18)) print(obj.age) setattr(obj, ‘show‘, lambda num: num + 1) print(obj.show(8)) # # # #### 删除成员 #### # delattr(obj, ‘name‘) # delattr(obj, ‘func‘) #反射代码示例
class Foo(object):
def __init__(self):
self.name = ‘wupeiqi‘
# self.age = age
def func(self):
print("func is running.")
return ‘func‘
obj = Foo()
# #### 检查是否含有成员 ####
print(hasattr(obj, ‘name‘))
print(hasattr(obj, ‘func‘))
# # #### 获取成员 ####
print(getattr(obj, ‘name‘))
print(getattr(obj, ‘func‘))
getattr(obj, ‘func‘)()
#
# # #### 设置成员 #### 相当于增加成员。
print(setattr(obj, ‘age‘, 18))
print(obj.age)
setattr(obj, ‘show‘, lambda num: num + 1)
print(obj.show(8))
#
# # #### 删除成员 ####
# delattr(obj, ‘name‘)
# delattr(obj, ‘func‘)
#反射代码示例