我定义了几个类
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类。你知道吗
不小心把“动物园”变成了“缩放”
The ^{} function 可以返回类的字段信息,包括每个字段的名称和类型。所以你的
list
理解可以写成:这里的缺陷是它不适用于字符串注释,这包括模块使用
from __future__ import annotations
的所有情况。您可以使用技巧here解析为实际类型,也可以无条件地获取所有字段,然后使用isinstance
检查对其进行筛选(验证运行时类型,而不是在运行时可以轻松忽略的带注释类型):相关问题 更多 >
编程相关推荐