Python Data Class Parameters
The below code is the function definition of the dataclass in python.
def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False):
There are six optional parameters that python data class takes:
- init
- repr
- eq
- order
- unsafe_hash
- frozen
we will learn about these parameters one by one.
Init Parameter In Python Data Class
This is the first optional parameter in the python data class and is set to True by default. This creates the initialization function for the class with the class attributes.
Example:
@dataclass
class Student():
name: str
clss: int
stu_id: int
In the above code we used dataclass decorator and thus just declared the class attributes with type hint.
When the init parameter is set to default i.e True. The code is converted to simple class with the init function defined.
class Student():
def __init__(self,name,clss,stu_id):
self.name = name
self.clss = clss
self.stu_id = stu_id
We can access the class attributes.
Example:
Access class attributes
student = Student('HTD', 10, 17)
>>> print(student.name)
HTD
>>> print(student.clss)
10
>>> print(student.stu_id)
17
Now letโs make the init parameter as false and see the effect.
@dataclass(init=False)
class Student():
name: str
clss: int
stu_id: int
>>> student = Student('HTD', 10, 17)
Traceback (most recent call last):
File ".\main.py", line 11, in <module>
student = Student('HTD', 10, 17)
TypeError: Student() takes no arguments
When there is no init function in a class this means there are no class attributes and thus the Student class doesnโt take any arguments.
Read about other Python Data Class Parameters from the original Post.
Top comments (0)