I have few classes that have same props and it will be much more of them so how I can make other class to pass that common props to each class but to use default values from Props
class if I do not want to enter some of the arguments. So far if I do not enter anchor
, layer
or linetype_scale
argument I am getting error TypeError: __init__() missing 3 required positional arguments: 'anchor', 'layer', and 'linetype_scale'
.
class Props():
def __init__(self, anchor="CC", layer=0, linetype_scale=1):
self.anchor = anchor
self.layer = layer,
self.linetype_scale = linetype_scale
class Rectangle(Props):
def __init__(self, x, y, width, height, anchor, layer, linetype_scale):
super().__init__(anchor, layer, linetype_scale)
self.x = x
self.y = y
self.width = width
self.height = height
class Square(Props):
def __init__(self, x, y, width, anchor, layer, linetype_scale):
super().__init__(anchor, layer, linetype_scale)
self.x = x
self.y = y
self.width = width
class Circle(Props):
def __init__(self, x, y, diametar, anchor, layer, linetype_scale):
super().__init__(anchor, layer, linetype_scale)
self.x = x
self.y = y
self.diametar = diametar
What I want to be able to do is to call class without passing arguments for example:
rect = Rectangle(10, 10, 20, 50)
but if i need to change anything to be able to do this:
rect = Rectangle(10, 10, 20, 50, linetype_scale=5)
CodePudding user response:
You could make use of **kwargs
, which are passed to Props
if given, otherwise the defaults from Props
are used:
class Props():
def __init__(self, anchor="CC", layer=0, linetype_scale=1):
self.anchor = anchor
self.layer = layer,
self.linetype_scale = linetype_scale
class Rectangle(Props):
def __init__(self, x, y, width, height, **kwargs):
super().__init__(**kwargs)
self.x = x
self.y = y
self.width = width
self.height = height
rect1 = Rectangle(10, 10, 20, 50)
rect2 = Rectangle(10, 10, 20, 50, linetype_scale=5)
print(rect1.linetype_scale)
print(rect2.linetype_scale)
Out:
1
5