【发布时间】:2019-04-24 12:19:34
【问题描述】:
假设我创建了一个名为 MyButton 的自定义 Button 类。我希望所有创建的 MyButton 在按下时播放相同的声音。但我也想为特定按钮添加不同的功能,例如我想要一些按钮来更改标签文本,但我也希望它们播放那个声音。有没有办法通过继承来做到这一点,这样我就不必记住我必须为每个创建的按钮添加播放声音功能?
编辑:假设我有一个 MyButton 类声明如下:
class MyButton(Button):
def generic_function_for_all_buttons(self):
print('GENERIC FUNCTION')
现在,当我尝试在代码中的其他位置创建 MyButton 时,如下所示:
class TestClass(BoxLayout):
def __init__(**kwargs):
self.buttons = []
self.set_layout()
def button_action(self,button):
button.generic_function_for_all_buttons()
print(button.text)
def set_layout(self):
for i in range(0,100):
button = MyButton(text=i)
button.on_press = functools.partial(button_action, button)
self.buttons.append(button)
self.add_widget(button)
这不是可运行的代码,只是我想要实现的演示。现在,每次我从 TestClass 中按下 MyButton 时,它都会根据按下的按钮打印 GENERIC FUNCTION 和 0-99 之间的数字。但是我必须添加 button.generic_function_for_all_buttons() 行,如果可能的话我想避免它。如果这 100 个按钮中的每一个都有自己不同的操作,如下所示:
def action_1(self,button):
button.generic_function_for_all_buttons()
print('1')
def action_2(self,button):
button.generic_function_for_all_buttons()
print('2')
def action_3(self,button):
button.generic_function_for_all_buttons()
print('3')
...
那个 button.generic_function_for_all_buttons() 是我想要避免的 100 行代码。我认为它必须以某种方式通过继承成为可能,例如我将 on_press 方法添加到 MyButton 类,如下所示:
class MyButton(Button):
def on_press(self):
print('GENERIC FUNCTION')
但它只是忽略它。
【问题讨论】:
标签: python inheritance button kivy