gpt4 book ai didi

python - 在数据类中创建类变量的正确方法

转载 作者:行者123 更新时间:2023-12-03 16:08:21 25 4
gpt4 key购买 nike

我刚刚开始使用Python的数据类,并且我想确认我以正确的方式声明了类变量。

使用常规python类

class Employee:

raise_amount = .05

def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay

使用python数据类
@dataclass
class Employee:
fname: str
lname: str
pay: int
raise_amount = .05

我要引用的类变量是 raise_amount。这是使用数据类正确声明的类变量吗?还是有更好的方法呢?

我已经测试了数据类实现,并且它提供了预期的功能,但是我主要想知道我的实现是否遵循最佳实践。

最佳答案

要创建类变量,请将该字段注释为 typing.ClassVar 或根本不注释。

from typing import ClassVar

@dataclass
class Foo:
ivar: float = 0.5
cvar: ClassVar[float] = 0.5
nvar = 0.5

foo = Foo()
Foo.ivar, Foo.cvar, Foo.nvar = 1, 1, 1
print(Foo().ivar, Foo().cvar, Foo().nvar) # 0.5 1 1
print(foo.ivar, foo.cvar, foo.nvar) # 0.5 1 1

有一个细微的区别,即 @dataclass完全忽略了未注释的字段,而 ClassVar字段已存储但未转换为属性。

dataclasses — Data Classes

The member variables [...] are defined using PEP 526 type annotations.

Class variables

One of two places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.

关于python - 在数据类中创建类变量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61937520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com