反射相关的四个函数hasattr、getattr、setattr、delattr,下面分别来演示每一个函数的用法。
- hasattr(obj, name_str)
判断对象obj里是否有对应的字符串name_str的方法
# Author: Mr.Xue
# 2019.10.30
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self):
print("%s is eating..." % self.name)
d = Dog("d")
choice = input(">>")
print(hasattr(d, choice))
测试结果如下:
xue@xue-MacBookAir:~/python_learn$ python3 fanshe.py
>>:eat
True
xue@xue-MacBookAir:~/python_learn$ python3 fanshe.py
>>:talk
False
- getattr(obj, name_str)
根据字符串去获取obj对象里的对应方法的内存地址
# Author: Mr.Xue
# 2019.10.30
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self):
print("%s is eating..." % self.name)
d = Dog("d") # 实例化
choice = input(">>:")
if hasattr(d, choice):
attr = getattr(d, choice) # 去获取choice方法的内存地址
print(attr) # 打印内存地址
attr() # 调用Dog类的这个方法
测试结果如下:
xue@xue-MacBookAir:~/python_learn$ python3 fanshe.py
>>:eat
<bound method Dog.eat of <__main__.Dog object at 0x7f81777e6588>>
d is eating...
- setattr(obj, name_str, func)
obj.name_str = func,一共是两种方式,一个是对于变量来说,一种是对于函数来说,看如下例子就能整明白
# Author: Mr.Xue
# 2019.10.30
def bulk(self): # 类外部定义的一个函数bulk
print("%s is bulking..." % self.name)
class Dog(object): # Dog类
def __init__(self, name):
self.name = name
def eat(self): # 类内的方法
print("%s is eating..." % self.name)
d = Dog("d") # 实例化
choice = input(">>:") # 用户输入
if hasattr(d, choice): # 判断d实例是否有choice方法
pass
else: # 没有
# 第一种:针对函数
# 给d对象添加用户输入的方法choice,方法功能实现和bulk一样
setattr(d, choice, bulk)
d.talk(d) # 假如用户输入‘talk’,这里是调用talk方法
# 第二种:针对变量
setattr(d, choice, 22) # 给d实例添加一个变量choice,值等于22
print(getattr(d, choice)) # 打印choice的值
输出测试结果如下:
xue@xue-MacBookAir:~/python_learn$ python3 fanshe.py
>>:talk
d is bulking...
22
- delattr(obj, name_str)
假如name_str存在于obj对象中,删除obj对象的name_str
# Author: Mr.Xue
# 2019.10.30
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self):
print("%s is eating..." % self.name)
d = Dog("d")
choice = input(">>:")
print(hasattr(d, choice)) # 在删除之前,看看方法还在不在
if hasattr(d, choice): # 有这个方法
delattr(d, choice) # 删除这个方法
print(hasattr(d, choice)) # 再次打印查看方法还在不在
测试输出结果如下:
xue@xue-MacBookAir:~/python_learn$ python3 fanshe.py
>>:eat
True
Traceback (most recent call last):
File "fanshe.py", line 18, in <module>
delattr(d, choice)
AttributeError: eat