Last active
August 9, 2021 09:21
-
-
Save aladinoster/2797ee06c034badd8045863d33d897fe to your computer and use it in GitHub Desktop.
Python: Dataclass initializations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass, field | |
@dataclass | |
class A: | |
x: int = 1 | |
y: int = 2 | |
z: int = 3 | |
def __init__(self, **kwargs): | |
valid_keys = ["x", "y", "z"] # This cleans all the fields | |
if kwargs: | |
for key in valid_keys: | |
setattr(self, key, kwargs.get(key)) | |
@dataclass | |
class B: | |
x: int = field(default=1, init=True) | |
y: int = field(default=2, init=True) | |
z: int = field(default=3, init=True) | |
def __post_init__(self, **kwargs): | |
for key in kwargs.keys(): | |
setattr(self, key, kwargs.get(key)) | |
if __name__ == "__main__": | |
a = A() | |
print(a) | |
b = B(x=2) | |
print(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment