I've just begun playing around with Python's Data Classes, and I would like confirm that I am declaring Class Variables in the proper way.
Using regular python classes
class Employee:
raise_amount = .05
def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay
Using python Data Class
@dataclass
class Employee:
fname: str
lname: str
pay: int
raise_amount = .05
The class variable I am referring to is raise_amount
. Is this a properly declared class variable using Data Classes? Or is there a better way of doing so?
I have tested the data class implementation already and it provides the expected functionality, but I am mainly wondering if my implementation is following best practices.
A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.
Class/Static Variables Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
In class-based, object-oriented programming, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. A class variable is not an instance variable. It is a special type of class attribute (or class property, field, or data member).
Variable defined inside the class: var_name. If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.
To create a class variable, annotate the field as a typing.ClassVar
or not at all.
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
There is a subtle difference in that the unannotated field is completely ignored by @dataclass
, whereas the ClassVar
field is stored but not converted to an attribute.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With