我有代码
class Button(object):
'''A simple Button class to represent a UI Button element'''
def __init__(self, text = "button"):
'''Create a Button and assign it a label'''
self.label = text
def press(self):
'''Simply print that the button was pressed'''
print("{0} was pressed".format(self.label))
class ToggleButton(Button):
def __init__(self, text, state=True):
super(ToggleButton, self).__init__(text)
self.state = state
def press(self):
super(ToggleButton, self).press()
self.state = not self.state
print('{0} is now'.format(self.label), 'ON' if self.state else 'OFF')
当我输入
tb = ToggleButton("Test", False)
tb.press()
tb.press()
它工作正常并返回
Test was pressed
Test is now ON
Test was pressed
Test is now OFF
但我想要的是让text参数可选,这样如果我输入
b = ToggleButton()
b.press()
它会返回
ToggleButton was pressed
ToggleButton is now OFF
任何帮助都会非常感激!
答案 0 :(得分:0)
按照state
参数的示例,同时为text
提供默认值。
class ToggleButton(Button):
def __init__(self, text="ToggleButton", state=True):
super(ToggleButton, self).__init__(text)
self.state = state
答案 1 :(得分:0)
考虑适应性如下:
class ToggleButton(Button):
def __init__(self, *args, **kwargs):
super(ToggleButton, self).__init__(*args)
self.state = kwargs.get('state', True)