Python 数据类从构造函数调用父字段
Python dataclass call parent field from constructor
是否可以继承数据 class 并在子构造函数中使用父字段?
import dataclasses
def get_id():
return "some unique id"
@dataclasses.dataclass
class Parent:
name: str
uid: str = dataclasses.field(default_factory=lambda: get_id())
@dataclasses.dataclass
class Child(Parent):
dependent_on_id: str = dataclasses.field(default_factory=lambda: f"with {super.uid}")
c = Child(name='x')
print("foo " + c.uid)
print(c.dependent_on_id)
输出:
Traceback (most recent call last):
File "stack_questions.py", line 17, in <module>
c = Child(name='x')
File "<string>", line 5, in __init__
File "stack_questions.py", line 14, in <lambda>
dependent_on_id: str = dataclasses.field(default_factory=lambda: f"with {super.uid}")
AttributeError: type object 'super' has no attribute 'uid'
想要输出:
foo some unique id
with foo some unique id
目前在我看来,我最好的解决方案是通过组合而不是继承来实现
super
在这种情况下没有意义。您可以使用数据类的 __post_init__
方法来设置 dependent_on_id
.
@dataclasses.dataclass
class Child(Parent):
dependent_on_id: str = None
def __post_init__(self):
if not self.dependent_on_id:
self.dependent_on_id = f"with {self.uid}" # you don't need super
是否可以继承数据 class 并在子构造函数中使用父字段?
import dataclasses
def get_id():
return "some unique id"
@dataclasses.dataclass
class Parent:
name: str
uid: str = dataclasses.field(default_factory=lambda: get_id())
@dataclasses.dataclass
class Child(Parent):
dependent_on_id: str = dataclasses.field(default_factory=lambda: f"with {super.uid}")
c = Child(name='x')
print("foo " + c.uid)
print(c.dependent_on_id)
输出:
Traceback (most recent call last):
File "stack_questions.py", line 17, in <module>
c = Child(name='x')
File "<string>", line 5, in __init__
File "stack_questions.py", line 14, in <lambda>
dependent_on_id: str = dataclasses.field(default_factory=lambda: f"with {super.uid}")
AttributeError: type object 'super' has no attribute 'uid'
想要输出:
foo some unique id
with foo some unique id
目前在我看来,我最好的解决方案是通过组合而不是继承来实现
super
在这种情况下没有意义。您可以使用数据类的 __post_init__
方法来设置 dependent_on_id
.
@dataclasses.dataclass
class Child(Parent):
dependent_on_id: str = None
def __post_init__(self):
if not self.dependent_on_id:
self.dependent_on_id = f"with {self.uid}" # you don't need super