Currently I used DTO(Data Transfer Object) like this.
class Test1:
def __init__(self,
user_id: int = None,
body: str = None):
self.user_id = user_id
self.body = body
Example code is very small, But when object scale growing up, I have to define every variable.
While digging into it, found that python 3.7 supported dataclass
Below code is DTO used dataclass.
from dataclasses import dataclass
@dataclass
class Test2:
user_id: int
body: str
In this case, How can I allow pass more argument that does not define into class Test2
?
If I used Test1
, it is easy. Just add **kwargs(asterisk)
into __init__
class Test1:
def __init__(self,
user_id: int = None,
body: str = None,
**kwargs):
self.user_id = user_id
self.body = body
But using dataclass, Can't found any way to implement it.
Is there any solution here?
Thanks.
EDIT
class Test1:
def __init__(self,
user_id: str = None,
body: str = None):
self.user_id = user_id
self.body = body
if __name__ == '__main__':
temp = {'user_id': 'hide', 'body': 'body test'}
t1 = Test1(**temp)
print(t1.__dict__)
Result : {'user_id': 'hide', 'body': 'body test'}
As you know, I want to insert data with dictionary type -> **temp
Reason to using asterisk in dataclass is the same.
I have to pass dictinary type to class init.
Any idea here?
See Question&Answers more detail:
os