0

我有代码

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

但我想要的是文本参数是可选的,这样如果我输入

b = ToggleButton()
b.press()

它会回来

ToggleButton was pressed
ToggleButton is now OFF

任何帮助将非常感激!

4

2 回答 2

0

考虑一些自适应的东西,例如:

class ToggleButton(Button):
    def __init__(self, *args, **kwargs):
        super(ToggleButton, self).__init__(*args)
        self.state = kwargs.get('state', True)
于 2013-05-24T03:08:17.357 回答
0

按照state参数的示例并给出text默认值。

class ToggleButton(Button):
    def __init__(self, text="ToggleButton", state=True):
        super(ToggleButton, self).__init__(text)
        self.state = state
于 2013-05-24T02:51:30.487 回答