反射
hasattr(obj, name_str) 判断一个对象obj里是否有对应的name_str字符串方法的方法
getattr(obj, name_str) 根据字符串获取obj对象里的对应方法的内存地址
setattr(obj, name_str) 添加新属性
delattr(obj, name_str) 删除属性
def job(self):
print("%s is working" % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eating %s." % (self.name,food))
d = Person('liming')
choice = input(">>:").strip()
if hasattr(d,choice):
func = getattr(d, choice) # 输入 eat
func("apple") # 调用 eat 方法
else:
setattr(d,choice,job) # 添加反射方法 输入work
d.work(d)
>>:eat
liming is eating apple.
>>:work
liming is working
def job(self):
print("%s is working" % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eating %s." % (self.name,food))
d = Person('liming')
choice = input(">>:").strip()
if hasattr(d,choice):
attr = getattr(d,choice) # 输入name
setattr(d,choice,"hanmeimei") # 修改属性
print(getattr(d, choice)) # 打印修改的属性
else:
setattr(d,choice,22) # 添加反射属性 输入 age
print(getattr(d,choice))
>>:name
hanmeimei
>>:age
22
def job(self):
print("%s is working" % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eating %s." % (self.name,food))
d = Person('liming')
choice = input(">>:").strip()
if hasattr(d,choice):
delattr(d,choice) # 删除属性
print(getattr(d, choice)) # 打印删除的属性
>>:name
Traceback (most recent call last):
File "D:/PyCharm/PycharmProjects/s12/day07/反射.py", line 21, in <module>
print(getattr(d, choice)) # 打印删除的属性
AttributeError: 'Person' object has no attribute 'name'