Skip to main content
 首页 » 编程设计

python之检查方法是否已经在对象中

2025年05月04日9langtianya

我正在尝试查看我的对象是否已经存在一个属性实例。正如您在下面看到的,如果我的 Dog 对象具有特定属性,我想通过 do_something_if_has_aged 方法执行某些操作。如何检查某个属性是否已经声明?通常你会用这样的东西检查是否存在,它返回 False:

obj = None 
if obj: 
    print(True) 
else: 
    print(False) 

这是我的最小可重现示例:

>>> class Dog: 
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
    def add_years(self, years): 
        self.age += years 
        self.has_aged = True 
    def do_something_if_has_aged(self): 
        if self.has_aged: 
            print("The dog has aged and is %d years closer to death" % self.years) 
        else: 
            print("The dog hasn't aged, apparently.") 
 
 
>>> dog = Dog('Spot', 3) 
>>> dog.age 
3 
>>> dog.do_something_if_has_aged() 
Traceback (most recent call last): 
  File "<pyshell#193>", line 1, in <module> 
    dog.do_something_if_has_aged() 
  File "<pyshell#190>", line 9, in do_something_if_has_aged 
    if not self.has_aged: 
AttributeError: 'Dog' object has no attribute 'has_aged' 
>>> dog.add_years(1) 
>>> dog.age 
4 
>>> dog.do_something_if_has_aged() 
The dog hasn't aged, apparently. 

不过,显然这只狗已经老了。

如果标题没有反射(reflect)我下面要表达的意思,我深表歉意;我是 OOP 新手。

请您参考如下方法:

看起来您正在寻找 hasattr内置函数:

>>> class Dog(object): 
...     pass 
... 
>>> a = Dog() 
>>> hasattr(a, 'age') 
False 
>>> a.age = 7 
>>> hasattr(a, 'age') 
True 

在你的情况下,你可以修改如下:

def do_something_if_has_aged(self): 
    if hasattr(self, 'has_aged'): 
        pass # do your logic