7.14 反射 (hasattr, getattr, setattr, delattr)
What is reflected
When we call the object method, you may want to use a string to call the corresponding method, we'll use reflection.
Reflection: is mapped to the attribute of the object as a string
- Use it to realize a reflection function:
- hasattr(o, name)
- getattr(o, name, [default])
- setattr(o, name, value)
- delattr(o, name)
class People:
country = 'China'
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self):
print('%s is talking' % self.name)
p1 = People('a', 12)
print(p1.name) # 当我们调用talk方法时,其实本质上是调用obj.__dict__['name']来实现的
# print(p1.'name') 会报错,因为 p1.name 中的 name 并不是一个字符串,即我们不能用 p1.'name' 来调用。
# 那么当我们想用字符串来调用方法的时候怎么做呢?
# 虽然我们可以用一下的方式来实现,但是python中提供了一种更好的解决方法:反射
str_name = 'name'
print(p1.__dict__[str_name])
# 反射的函数:hasattr(o, name) getattr(o, name, [default])
print(hasattr(p1, 'name')) # 判断 p1 对象(即__dict__里)有没有 'name' 属性
print(getattr(p1, 'namexxxx', None)) # 取得namexxxx属性,当没有这个属性会报错。最后一个参数可以设定没有属性时候的返回值
setattr(p1, 'name', 'kaka') # 设定属性值
print(p1.__dict__)
delattr(p1, 'age') # 删除属性
print(p1.__dict__)
print(getattr(People, 'country')) # 同样适用于类的属性
Results of the:
a
a
True
None
{'name': 'kaka', 'age': 12}
{'name': 'kaka'}
Reflected Application
Method accepts user input, to call the class
class Service:
def __init__(self):
pass
def run(self):
while True:
cmd = input('>>: ').strip()
if hasattr(self, cmd):
func = getattr(self, cmd) # 获取属性
func() # 调用属性,这个很容易忽视,需要注意
else:
print('no this method')
def get(self):
print('get......')
def put(self):
print('put......')
s1 = Service()
s1.run()