如何在扩展自同一父类的类中获取属性

2024-04-26 12:31:48 发布

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

我定义了几个类

class Animal:
    def do_parent_method():
        pass

class Monkey(Animal):
    pass


class Elephant(Animal):
    pass


@dataclass
class Zoo:
    monkey: Monkey= Monkey()
    elephant: Elephant = Elephant()
    start_time: datetime = None
    name: str = 'Not important at all'

    def data_format(self):
        items = [self.monkey, self.elephant]  # Now I hard code here
        for item in items:
            do_something()

关键是如何在Zoo类中获取属性

也许有一天,我们会在代码中添加另一种动物

@dataclass
class Zoo:
    monkey: Monkey= Monkey()
    elephant: Elephant = Elephant()
    start_time: datetime = None
    name: str = 'Not important at all'

    def data_format(self):
        items = [get the attributes that extends from Animal]  # How to do?
        for item in items:
            do_parent_method()

现在我只想items成为一个列表,这样我就可以循环它了。你知道吗

或者你有别的好主意对我也有好处。你知道吗

注:

Zoom类中的所有属性将只有一些str、datetime和int类型。所有其他实例都将是Animal类的children类。你知道吗

固定:

不小心把“动物园”变成了“缩放”


Tags: selfdatetimedefitemspassdoclassmonkey
1条回答
网友
1楼 · 发布于 2024-04-26 12:31:48

The ^{} function可以返回类的字段信息,包括每个字段的名称和类型。所以你的list理解可以写成:

items = [getattr(self, field.name) for field in fields(self) if issubclass(field.type, Animal)]

这里的缺陷是它不适用于字符串注释,这包括模块使用from __future__ import annotations的所有情况。您可以使用技巧here解析为实际类型,也可以无条件地获取所有字段,然后使用isinstance检查对其进行筛选(验证运行时类型,而不是在运行时可以轻松忽略的带注释类型):

items = [attr for attr in (getattr(self, field.name) for field in fields(self)) if isinstance(attr, Animal)]

相关问题 更多 >