(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()

运行结果为:


猜你喜欢

转载自blog.csdn.net/miaoqinian/article/details/79969511