Python 反射

python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

四个实现反射(自省)的函数为:getattr, setattr delattr,hasattr

class Foo:
    f = '类的静态变量'
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def say_hi(self):
        print('hi,%s'%self.name)

obj=Foo('andy',23)

#检测是否含有某属性
print(hasattr(obj,'name'))
print(hasattr(obj,'say_hi'))

#获取属性,如果不存在,则报错
name=getattr(obj,'name')
print(name)
func=getattr(obj,'say_hi')
func()


#设置属性
setattr(obj,'show_info',lambda self:self.name+ str(self.age))
print(obj.show_info(obj))

#删除属性
delattr(obj,'age')

print(obj.__dict__)

#输出
(base_env) andy@Andy963:/mnt/c/Users/Andy/Desktop$ python code.py
True
True
andy
hi,andy
andy23
{'name': 'andy', 'show_info': <function <lambda> at 0x7f72e12a2e18>}

这里需要注意一点,在我setattr后我调用show_info时,调用类方法,需要传入self,这时self即我们实例化的obj

 

类反射:

class Foo(object):

    staticField = "I'm static"

    def __init__(self):
        self.name = 'andy'

    def func(self):
        return 'func'

    @staticmethod
    def bar():
        return 'bar'

print(getattr(Foo, 'staticField'))
print(getattr(Foo, 'func')(Foo))
print(getattr(Foo, 'bar'))

同样,通过getattr得到fun函数对象时,添加括号即可执行,但要带上Foo类本身作为参数。

 

当前模块的反射:

import sys

def s1():
    print('s1')


def s2():
    print('s2')


this_module = sys.modules[__name__]

print(hasattr(this_module, 's1'))
print(getattr(this_module, 's2'))

 

上一篇:Python 可迭代对象与迭代器

下一篇:Python 函数 与 方法判断