Python 数据类中的继承

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

我不知不觉地发现了数据类的这种行为。数据类如果在子级中继承并重写,则由于签名不匹配而无法重写。

from dataclasses import dataclass

@dataclass
class base:
  x: str = "parent"

@dataclass
class child(base):
  x = "child"

config = child()
print(config.x)  # --> parent

原因是变量的签名。如果我用其他方法的话。

from dataclasses import dataclass

@dataclass
class base:
  x = "parent"

@dataclass
class child(base):
  x: str = "child"

config = child()
print(config.x)  # --> child

我不知道这是否是理想的行为或数据类所期望的行为,或者是一个需要解决的错误。

python inheritance python-dataclasses
1个回答
0
投票

所以我的答案是来自观察,所以请持保留态度:

这是我编写的一些代码来解释结果

@dataclass
class base:
   y: str = "parent"

@dataclass
class child(base):
   x = "child"

config = child()
print(config)
print(config.x)

输出:

child(y='parent')
child

正如您在打印类时所看到的,它显示它的 y 变量中有“parent”,但没有带有“child”的 x 变量。重要的是要注意我定义了 y 的变量类型

我的答案是,你正在使用一个需要你定义变量类型的模块,所以当你不定义变量类型时,事情就会开始变得“错误”,但我的猜测是它只是默认回到基本的Python类属性当您不定义它时,装饰器会用已定义其类型并理解的变量覆盖它

编辑:

经过进一步检查,它在文档中提到,可以在here找到:

这些生成的方法中使用的成员变量是使用 PEP 526 类型注释定义的

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