python之反射

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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值