(python)与反射有关的内置函数

两个与反射无关的内置方法:

isinstance(obj,cls)判断一个对象是不是一个类的实例。

issubclass(cls,obeject)判断一个类是不是一个类的子类。

下面介绍与反射有关的内置函数。

下面四个函数是专门来操作类与对象属性的,通过字符串来操作类与对象的属性,这种操作称为反射。





class People:
    country='China'
    def __init__(self,name):
        self.name=name
    def tell(self):
        print('%s is aaa' %self.name)

obj=People('monicx')
#hasattr函数
print('country'in People.__dict__)#判断一下属性是否存在
print(hasattr(People,'country'))
print(hasattr(People,'tell'))
print(hasattr(People,'name'))

#getattr函数
print(getattr(People,'country'))#China
print(getattr(People,'tell',None))#<function People.tell at 0x00000000026BA950>

#setattr函数
# People.x=11111
setattr(People,'x',11111)
print(People.x)
#obj.age=18
setattr(obj,'age',18)

#delattr函数
# del People.country
delattr(People,'country')
print(People.__dict__)
#del obj.name
delattr(obj,'name')
print(obj.__dict__)

下面来一个反射的简单应用场景。

当用户输入命令的时候能够反射到对应的功能上:

class Foo:
    def run(self):
        while True:
            cmd=input('cmd>>:').strip()#用户输入反射到它的功能上
            # print('%s run....'%cmd)
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()

    def download(self):
        print('download....')

    def upload(self):
        print('upload')
obj=Foo()
obj.run()

运行结果为:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值