簡體   English   中英

python非特定參數

[英]python non-specific argument

我有代碼

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

任何幫助將非常感激!

遵循state參數的示例,並為text一個默認值。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM