python反射之访问对象的属性

168 阅读1分钟

1 hasattr方法

该方法是用于判断对象中有没有方法或者属性

class Person(object):
​
    def __init__(self, name):
        self.name = name
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
p = Person("小明")
print(hasattr(p, 'name'))
print(hasattr(p, 'say'))
print(hasattr(p, 'fly'))

result:

True
True
False

2 getattr方法

该方法是用于获取对象中的方法或者属性

class Person(object):
​
    def __init__(self, name):
        self.name = name
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
p = Person("小明")
print(getattr(p, 'name'))
print(getattr(p, 'say'))
f = getattr(p, 'say')
f()

result:

小明
<bound method Person.say of <__main__.Person object at 0x00000000023F8400>>
小明在谈话

对于属性,获取的是值;对于方法,获取的是其内存地址

print(getattr(p, 'fly'))

result:

AttributeError: 'Person' object has no attribute 'fly'

对于不存在的方法或属性,默认情形下直接报错

print(getattr(p, 'fly', '找不到该属性或方法'))

result:

找不到该属性或方法

可以利用getattr方法的第三个参数在找不到属性或方法时自定义返回消息,而不是报错

3 setattr方法

该方法主要用于给对象增加属性或方法

class Person(object):
    def __init__(self, name):
        self.name = name
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
def fly(self):
    print(f"{self.name}在飞")
​
​
p = Person("小明")
setattr(p, "fly", fly)
p.fly(p)

result:

小明在飞
setattr(p, "age", 89)
print(p.age)

result:

89

4 delattr方法

该方法用于删除对象中的属性,但是不能删除方法

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
p = Person("小明", 23)
delattr(p, "age")
print(p.age)

result:

AttributeError: 'Person' object has no attribute 'age'

5 dir方法

该方法用于返回当前的属性名列表,特殊属性不包含在该列表中

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
​
    def say(self):
        print(f"{self.name}在谈话")
​
​
p = Person("小明", 23)
print(dir(p))

result:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say']