初学Python类

时间:2013-05-24 02:18:00

标签: python class button

我目前有这个代码,如果按下ToggleButton我想要它说

ToggleButton was pressed

然后说明ToggleButton是打开还是关闭(默认情况下它是打开的,如果按下按钮它将被关闭)我想通过状态为True或False进行此操作,但我不确定这该怎么做。 任何帮助将不胜感激

class Button(object):

    def __init__(self, text = "button"):
        self.label = text

    def press(self):
        print("{0} was pressed".format(self.label))
class ToggleButton(Button):

   def __init__(self, text="ToggleButton", state=True):
        self.label = text

例如我想要

b = ToggleButton()
b.press()

要返回:

ToggleButton was pressed
ToggleButton is now OFF

谢谢!

2 个答案:

答案 0 :(得分:1)

只需添加self.state变量:

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

    def press(self):
        super(ToggleButton, self).press()
        self.state = not self.state
        print('ToggleButton is now', 'ON' if self.state else 'OFF')

答案 1 :(得分:0)

我认为其他答案还没有完全回答你的问题,所以我会试一试。您已经将类层次结构设置得很好;你现在需要做的是覆盖press方法来处理新数据(切换当前状态)。这很简单!考虑以下课程:

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

    def press(self):
        # Call the superclass press() method
        # Note that pre-Python 3, the call needs to be super(ToggleButton,self)
        super().press()

        # Toggle state
        self.state = not self.state

        # Print current state
        print('{0} is now {1}'.format(self.label,'ON' if self.state else 'OFF'))

新的press方法只做三件事:

  • 首先,它调用超类(press)的Button方法。这可以防止您必须复制代码以打印“按下按钮”,或者您可能最终放入基础Button类的任何其他代码!
  • 其次,它切换当前状态。这部分不需要太多解释!
  • 最后,它打印出一条关于按钮新状态的消息。

这就是它的全部!我希望这会为你解决这个过程。