首页 > 技术文章 > python面向对象的反射

feifeifeisir 2018-09-01 22:31 原文

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

getattr # 根据字符串的形式,去对象中找成员。
hasattr # 根据字符串的形式,去判断对象中是否有成员。
setattr # 根据字符串的形式,去判断对象动态的设置一个成员(内存)
delattr # 根据字符串的形式,去判断对象动态的设置一个成员(内存)

1、对象应用反射
class Foo:
    def __init__(self):
        self.name = 'egon'
        self.age = 51
    def func(self):
        print('hello')
egg = Foo()

print(hasattr(egg,'name'))      #先判断name在egg里面存在不存在,结果是True
print(getattr(egg,'name'))      #如果为True它才去得到,结果是egon
print(hasattr(egg,'func'))     #结果是True
print(getattr(egg,'func'))     #得到的是地址<bound method Foo.func of <__main__.Foo object at 0x0000000001DDA2E8>>
getattr(egg,'func')()        #在这里加括号才能得到,因为func是方法,结果是hello

一般用法如下,先判断是否hasattr,然后取getattr
if hasattr(egg,'func'):
    getattr(egg,'func')()   #结果是hello
else:
    print('没找到')

2、类应用反射

class Foo:
    f = 123
    @classmethod
    def class_method_dome(cls):
        print('class_method_dome')
    @staticmethod
    def static_method_dome():
        print('static_method_dome')
        
print(hasattr(Foo,'class_method_dome'))         #结果是True
method = getattr(Foo,'class_method_dome')
method()                               #结果是class_method_dome

print(hasattr(Foo,'static_method_dome'))         #结果是True
method1 = getattr(Foo,'static_method_dome')
method1()                              #结果是static_method_dome

 

推荐阅读