我有幾個具有相同道具的類,而且它們會更多,所以我如何讓其他類將這些通用道具傳遞給每個類,但Props如果我不想輸入某些引數,則使用類中的默認值。到目前為止,如果我不進 anchor,layer或linetype_scale論點我得到的錯誤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
我想要做的是在不傳遞引數的情況下呼叫類,例如:
rect = Rectangle(10, 10, 20, 50)
但如果我需要改變任何東西才能做到這一點:
rect = Rectangle(10, 10, 20, 50, linetype_scale=5)
uj5u.com熱心網友回復:
您可以使用**kwargs,Props如果給定,則將其傳遞給,否則使用默認值 from Props:
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)
出去:
1
5
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345155.html
