在数据 Class 中创建 class 变量的正确方法
Proper way to create class variable in Data Class
我刚刚开始使用 Python 的数据 Classes,我想确认我是否以正确的方式声明了 Class 变量。
使用常规 python classes
class Employee:
raise_amount = .05
def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay
使用 python 数据 Class
@dataclass
class Employee:
fname: str
lname: str
pay: int
raise_amount = .05
我指的class变量是raise_amount
。这是使用 Data Classes 正确声明的 class 变量吗?或者有更好的方法吗?
我已经测试了数据 class 实现,它提供了预期的功能,但我主要想知道我的实现是否遵循了最佳实践。
要创建 class 变量,请将字段注释为 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 的数据 Classes,我想确认我是否以正确的方式声明了 Class 变量。
使用常规 python classes
class Employee:
raise_amount = .05
def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay
使用 python 数据 Class
@dataclass
class Employee:
fname: str
lname: str
pay: int
raise_amount = .05
我指的class变量是raise_amount
。这是使用 Data Classes 正确声明的 class 变量吗?或者有更好的方法吗?
我已经测试了数据 class 实现,它提供了预期的功能,但我主要想知道我的实现是否遵循了最佳实践。
要创建 class 变量,请将字段注释为 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 ClassesThe 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 istyping.ClassVar
. If a field is aClassVar
, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. SuchClassVar
pseudo-fields are not returned by the module-level fields() function.