python非特定参数

python非特定参数,python,arguments,Python,Arguments,我有密码 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

我有密码

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

任何帮助都将不胜感激

遵循
状态
参数的示例,并为
文本
提供默认值

class ToggleButton(Button):
    def __init__(self, text="ToggleButton", state=True):
        super(ToggleButton, self).__init__(text)
        self.state = state

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

class ToggleButton(Button):
    def __init__(self, *args, **kwargs):
        super(ToggleButton, self).__init__(*args)
        self.state = kwargs.get('state', True)