当成员函数不存在时为类对象分配默认值

问题描述 投票:0回答:1

我意识到我在尝试使其易于重现时过于简单化了我之前的问题

我想要的是在该输入值上运行一个成员函数并将结果分配给一个属性,但如果输入值没有该函数,则给出一个默认值,即:

class Puzzle:
    def __init__(self, random_object):
        self.name = random_object.getID() or "Dummy Value"
        self.score = random_object.getScore() or 0

如果

random_object.getID()
函数不存在,我会得到一个
AttributeError
:

>>> p = Puzzle("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
AttributeError: 'str' object has no attribute 'getID'

简洁地执行此操作的唯一方法是检查 AttributeError 吗?如果我有多个想要像这样分配的东西怎么办?

class Puzzle:
    def __init__(self, random_object):
        try:
            self.name = random_object.getID()
            self.score = random_object.getScore()
        except AttributeError as att:
            if att.name == "getID":
                self.name = "Dummy Value"
            elif att.name == "getScore":
                self.score = 0

我认为上面的块只能捕获其中一个异常并错过分配另一个值。我怎样才能抓住剩下的?

python initialization attributeerror
1个回答
0
投票

我从这个答案看到的是尝试

hasattr

class Puzzle:
    def __init__(self, obj):
        self.name = obj.id if hasattr(obj, "id") else "Dummy"
        self.score = obj.score() if hasattr(obj, "score") else 0

到目前为止,这似乎对我有用。有没有更简洁的方法?

© www.soinside.com 2019 - 2024. All rights reserved.