首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用dataclass子类覆盖非dataclass属性会导致属性错误。

用dataclass子类覆盖非dataclass属性会导致属性错误。
EN

Stack Overflow用户
提问于 2020-12-16 14:48:42
回答 1查看 330关注 0票数 0

给定以下数据模型

代码语言:javascript
复制
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

  • We继承

  • 我们不想在A

  • We实例化时设置参数a希望能够在B

实例化时设置参数a

以下是我想要工作的

代码语言:javascript
复制
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

代码语言:javascript
复制
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使用整数类型,则可以使用以下方法,表明理论上我所做的工作是可以的,但我表示的不正确:

代码语言:javascript
复制
from typing import List
from dataclasses import dataclass, field

class A:
    a: int = 1

@dataclass
class B(A):
    b: str
    a: int

我在这里做错什么了?如何将它作为a中的空列表在B中使用?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-16 15:41:48

我引用dataclasses模块中引发错误的片段(函数_process_class):

代码语言:javascript
复制
    # 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)

我认为这些评论表明,实现并不期望它必须处理继承的属性。我认为这意味着只有经过处理的属性才能被继承,即它们必须来自基本数据类型。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65325575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档