I have, for example, this class:
from dataclasses import dataclass
@dataclass
class Example:
name: str = "Hello"
size: int = 10
I want to be able to return a dictionary of this class without calling a to_dict function, dict or dataclasses.asdict each time I instantiate, like:
e = Example()
print(e)
{'name': 'Hello', 'size': 5}
What I have tried and did not work is ineriting from dict and callint dict.init inside Example's init, it seems to not recognize the name and size
Is there a nice solution to this?
Editing: my goal is that type(e) will be dict and not str, returning the dict from init is not possible, also, the keys and values should be obtained dynamically, and the values for name and size might change depending on the instantiations
CodePudding user response:
python class can provide a specific method to create a string representation:
def __str__(self):
Same as toString() java method.
CodePudding user response:
Override __str__
method:
from dataclasses import dataclass
@dataclass
class Example:
name: str = "Hello"
size: int = 10
def __str__(self):
return repr(self.__dict__)
e = Example()
print(e) # Use __str__ method
Output:
{'name': 'Hello', 'size': 10}
CodePudding user response:
Here is a solution by using __new__
from dataclasses import dataclass
@dataclass
class Example:
name: str
size: int
def __init__(self, name, size):
self.name = name
self.size = size
def __new__(cls, *args, **kwargs):
return kwargs
e = Example(**{"name":"Hello", "size":10})
print(e)
>>>> out :
>>>> {'name': 'Hello', 'size': 10}