【发布时间】:2017-02-24 05:08:46
【问题描述】:
我正在尝试查看我的对象是否已经存在某个属性的实例。正如您在下面看到的,如果我的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.
不过,很明显这只狗已经变老了。
如果标题没有反映我在下面试图传达的内容,我深表歉意;我是 OOP 的新手。
【问题讨论】:
-
你的情况是错误的:你应该这样做
if self.has_aged。
标签: python class oop attributes instance