[英]Overriding non dataclass attribute with dataclass subclass causes attribute error
給定以下數據模型
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
事實
A
不能成為dataclass
是福音(這會使問題變得微不足道)B
繼承A
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
如果我使用 integer 類型代替a
,則以下工作,表明理論上我所做的是可以的,但我表達不正確:
from typing import List
from dataclasses import dataclass, field
class A:
a: int = 1
@dataclass
class B(A):
b: str
a: int
我在這里做錯了什么? 我如何讓它在B
中a
空列表使用
我引用了引發錯誤的數據類模塊中的_process_class
dataclasses
:
# 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)
我認為評論表明實現並不期望它必須處理繼承的屬性。 我認為這意味着只能繼承處理過的屬性,即它們必須來自基本數據類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.