如何正确使用数据类'kw_only'?

问题描述 投票:0回答:1

我希望基类变量有默认值,而派生类变量没有默认值。 我在以下位置读过有关“kw_only”的内容:

https://medium.com/@aniscampos/python-dataclass-inheritance-finally-686eaf60fbb5

并在我的代码上尝试过:

from dataclasses import dataclass, field

@dataclass(kw_only=True)
class Base:
    c:int = field(default=8, compare=False)
    def printBVars(self):
        print("Base:", self.c)

@dataclass(kw_only=True)
class Derive(Base):
    cc:int = field()
    def printDVars(self):
        super().printBVars()
        print("Derive:", self.cc)


a = Derive()
a.printDVars()

但是 Python 给出了这个错误:

File "<string>", line 8, in <module> TypeError: dataclass() got an unexpected keyword argument 'kw_only' 

我做错了什么? 我使用 python 3.9 我已经阅读了谷歌的一些解决方案建议,尝试了一些但没有帮助。比如运行:

pip install attrs --upgrade

python python-3.x python-dataclasses
1个回答
0
投票

你应该将python版本更新到3.11
通过下面图片中的代码,您不能使用 kw_only 。

© www.soinside.com 2019 - 2024. All rights reserved.