1.

Python Dataclasses

Answer»

Python Classes used for storing data objects are called Dataclasses. They have certain features like:


  • Comparison with other objects of the same type is possible.

  • Stores data, representing a particular data type.

Python 2.7:

The example shows the performing function of Dataclasses in older versions of python when Dataclasses were not yet introduced.

class Self:
def __init__(self, x):
self.x = x

ob = Self("One")
print(ob.x)
Output:
One

Python 3.7:

The example shows using dataclasses in newer versions of python.

@dataclass #annotation indicates that it is a dataclass module
class Self:
x: string
ob = Self("One")
print(ob.x)
Output:
One

Note: It is compulsory to specify the datatype of each variable declared. If at any point we don’t want to specify the type, set the type as typing.Any.

from dataclasses import dataclass
from typing import Any
@dataclass
class WithoutExplicitTypes:
name: Any
age: Any = 16


Discussion

No Comment Found