检查方法是否已在对象中的实例中?

2024-04-20 13:02:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试查看我的对象是否已经存在属性的实例。正如您在下面看到的,如果我的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新手。你知道吗


Tags: thenameselfageif属性defdo
3条回答

我将重写__init__方法以包含self.has_aged = False以避免进行检查:

class Dog(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.has_aged = False # Starting value so it is guaranteed to be defined (unless explicitly deleted).

现在,你们班的其他同学应该按照书面形式来学习。但是,如果要查看对象上是否定义了属性,可以编写以下命令:

class Foo(object):
    def set_bar(self):
        self.bar = True # Define the attribute bar if it is not yet defined.

    def is_bar_set(self):
        return hasattr(self, 'bar')

看起来您正在寻找^{}内置函数:

>>> 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

与其测试属性,不如在类上设置一个默认值;如果实例属性丢失,Python将改为查找class属性:

class Dog:
    has_aged = False  # default for all instances
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def add_years(self, years):
        self.age += years
        self.has_aged = True  # sets an instance attribute
    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.")

(注意,如果self.has_aged真的您想进入第一个分支,而不是相反的分支,我必须反转您的测试)。你知道吗

或者可以在__init__中为属性设置默认值:

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.has_aged = False
    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.")

您还可以测试属性是否与^{} function一起存在:

def do_something_if_has_aged(self):
    if hasattr(self 'has_aged') and 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.")

或者使用带有默认值的^{} function

def do_something_if_has_aged(self):
    if not getattr(self 'has_aged', False):
        print("The dog has aged and is %d years closer to death" % self.years)
    else:
        print("The dog hasn't aged, apparently.")

但是,动态测试属性不应该是您选择的第一个选项;拥有一个类默认值要干净得多。你知道吗

相关问题 更多 >