DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Updated on

Python Data Class Parameters

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):
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
Traceback (most recent call last):
  File ".\main.py", line 11, in <module>
    student = Student('HTD', 10, 17)   
TypeError: Student() takes no arguments
Enter fullscreen mode Exit fullscreen mode

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)