I want to define in Python 3.9 a class which gets as a parameter a dictionary or a list of arguments and sets the class attributes in the following matter:
- If the key name is passed in the argument it uses it to set the corresponding class attribute.
- If the key name is not passed, it sets the class attribute with a default value.
One way to do this is:
class example():
def __init__(self, x=None, y=None):
if x is None:
self.x = "default_x"
else:
self.x = x
if y is None:
self.y = "default_y"
else:
self.y = y
or shortly (thank to matszwecja):
class example():
def __init__(self, x="default_x", y="default_y"):
self.x = x
self.y = y
Is there a more Pythonic way to do so without hard-coding if to each parameter? I want some flexibility so that if I add another attribute in the future, I won't be needed to hard-code another if for it.
I want to declare a class with
class example():
def __init__(kwargs):
?
Such as if I pass example(y="some", z=1, w=2) it will generate
self.x = "default_x"
self.y = "some"
self.z = 1
self.w = 2
x = 'default_x'instead ofx=None? That's literally what default is for.Nonefor some reason instead of the actual default value you want.self.xfrom the arguments?