InterviewSolution
| 1. |
What are important features of dataclasses in Python? |
|
Answer» The dataclasses module is one of the most recent modules to be added in Python's standard library. It has been INTRODUCED since version 3.7 and defines @dataclass decorator that automatically generates following methods in a user defined class: constructor METHOD __init__() STRING representation method __repr__() __eq__() method which overloads == operatorThe dataclass function decorator has following prototype: @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)All the arguments are of Boolean value. Each decides whether a corresponding magic method will be automatically generated or not. The 'init' parameter is True by default which will automatically generate __init__() method for the class. Let us define Employee class using dataclass decorator as follows: #data_class.py from dataclasses import dataclass @dataclass class Employee(object): NAME : str age : int salary : floatThe auto-generated __init__() method is like: def __init__(self, name: str, age: int, salary: float): self.name = name self.age = age self.salary = salaryAuto-generation will not happen if the class contsins explicit definition of __init__() method. The repr argument is ALSO true by default. A __repr__() method will be generated. Again the repr string will not be auto-generated if class provides explicit definition. The eq argument forces __eq__() method to be generated. This method gets called in response to equals comparison operator (==). Similarly other operator overloading magic methods will be generated if the order argument is true (the default is False), __lt__(), __le__(), __gt__(), and __ge__() methods will be generated, they implement comparison operators < <= > ans >= respectively. If unsafe_hash argument is set to False (the default), a __hash__() method is generated according to how eq and frozen are set. frozen argument: If true (the default is False), it emulates read-only frozen instances. >>> from data_class import Employee >>> e1=Employee('XYZ', 21, 2150.50) >>> e2=Employee('xyz', 20, 5000.00) >>> e1==e2 FalseOther useful functions in this module are as follows: asdict(): This function converts class instance into a dictionary object. >>> import dataclasses >>> dataclasses.asdict(e1) {'name': 'XYZ', 'age': 21, 'salary': 2150.5}astuple(): This function converts class instance into a tuple object. >>> dataclasses.astuple(e2) ('xyz', 20, 5000.0)make_dataclass(): This function creates a new dataclass from the list of tuples given as fields argument. >>> NewClass=dataclasses.make_dataclass('NewClass', [('x',int),('y',float)]) >>> n=NewClass(10,20) >>> n NewClass(x=10, y=20) |
|