python之反射
公共代码:
class Dog(object):
'''定义了一个Dog的类,有一个shout方法,并创建了一个名字为HaBa的dog实例'''
def __init__(self,name):
self.name=name
def shout(self):
print("The dog is shouting:Wang Wang Wang")
def eat(self,food):
print("The dog is eating %s"%food)
dog=Dog("HaBa")
choice=input("input your choice:")
1.hasattr(obj,string)
判断对象obj中有没有名字是string的方法,返回布尔值
result=hasattr(dog,choice)
print("result=",result)
运行结果
input your choice:shout
result= True
2.getattr(obj,string)
从对象obj中获得名字为string的方法,返回方法的地址
fun=getattr(dog,choice)
dog_food="gutou"
fun(dog_food)
运行结果
input your choice:eat
The dog is eating gutou
3.setattr(obj,x,value)
等价于obj.x=value,即给对象中的x赋值为value。
setattr(dog,choice,dog_sleep)
fun2=getattr(dog,choice)
fun2(dog)
运行结果
input your choice:sleep
HaBa is sleeping...
4.delattr(obj,x)
删除对象obj中的x
if hasattr(dog,choice):
delattr(dog,choice)
print("%s"%dog.name)
else:
print("your choice isn't exist!")
运行结果
input your choice:name
Traceback (most recent call last):
File "E:/Code/python workplace/project/类/反射.py", line 34, in <module>
print("%s"%dog.name)
AttributeError: 'Dog' object has no attribute 'name'
1758

被折叠的 条评论
为什么被折叠?



