python面向对象的反射

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

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

一、对象应用反射
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('没找到')

二、类应用反射dom

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
相关文章
相关标签/搜索