给定以下数据模型
from typing import List
class A:
a: List[int] = []
class B(A):
def __init__(self, b: str, a: List[int] = []):
self.b = b
self.a = a事实
‘我们想通过B
A
a希望能够在B
实例化时设置参数a
以下是我想要工作的
from typing import List
from dataclasses import dataclass, field
class A:
a: List[int] = []
@dataclass
class B(A):
b: str
a: List[int]纠正我得到的错误ValueError: mutable default <class 'list'> for field babies is not allowed: use default_factory
from typing import List
from dataclasses import dataclass, field
class A:
a: List[int] = field(default_factory=list)
@dataclass
class B(A):
b: str
a: List[int]但这会产生以下错误AttributeError: a
如果我对a使用整数类型,则可以使用以下方法,表明理论上我所做的工作是可以的,但我表示的不正确:
from typing import List
from dataclasses import dataclass, field
class A:
a: int = 1
@dataclass
class B(A):
b: str
a: int我在这里做错什么了?如何将它作为a中的空列表在B中使用?
发布于 2020-12-16 15:41:48
我引用dataclasses模块中引发错误的片段(函数_process_class):
# If the class attribute (which is the default value for this
# field) exists and is of type 'Field', replace it with the
# real default. This is so that normal class introspection
# sees a real default value, not a Field.
if isinstance(getattr(cls, f.name, None), Field):
if f.default is MISSING:
# If there's no default, delete the class attribute.
# This happens if we specify field(repr=False), for
# example (that is, we specified a field object, but
# no default value). Also if we're using a default
# factory. The class attribute should not be set at
# all in the post-processed class.
delattr(cls, f.name)
else:
setattr(cls, f.name, f.default)我认为这些评论表明,实现并不期望它必须处理继承的属性。我认为这意味着只有经过处理的属性才能被继承,即它们必须来自基本数据类型。
https://stackoverflow.com/questions/65325575
复制相似问题