使用接口时未使用的参数
问题描述:
我正在使用Python为我的一个项目创建一个GUI。尽管这是一个私人项目,但我想使用良好的编码实践。首先,请允许我介绍一下我的GUI模块的简化版本:使用接口时未使用的参数
# Just a box, can have borders or it can be filled
class Box(object):
def __init__(self):
# Set initial state
def update(self, xy, press):
# I'm just a dummy box, I don't care about xy or press
pass
def draw(self):
# Draw
# Like a box but with special functionality
class Button(Box):
def __init__(self):
super(Button, self).__init__()
# Set initial state
def update(self, xy, press):
# Do something with xy and press
# Like a box but with special functionality
class Status(Box):
def __init__(self):
super(Status, self).__init__()
# Set initial state
def update(self, xy, press):
# Do something with xy, ignore press
# A box which can hold boxes inside it to group them
class Container(Box):
def __init__(self):
super(Container, self).__init__()
self.childs = deque()
def update(self, xy, press):
for c in self.childs:
c.update(xy, press)
# Container draws itself like a Box but also draws boxes inside it
def draw(self):
super(Container, self).draw()
for c in self.childs:
c.draw()
每个GUI组件处于容器。 Container的 update()在每个周期被调用以更新那些包含最新输入信息的组件的状态。
我喜欢这个解决方案,因为它允许我使用一个接口在一个循环中更新整个GUI,并节省了一些代码。我的问题是,这些孩子中的一些需要比其他人更多的信息来更新他们的状态,并通过使用界面导致未使用的参数。
那么,在这种情况下,是否使用了未使用的参数被认为是不好的做法,我应该放弃使用接口?
答
通常的做法是称为协作式继承,它基本上只是一个流行词,说超级和子类都期望对方处于周围并传递它可能不需要的信息。这种类型的方法往往是这样的:换句话说
def foo(self, specific, arguments, *args, **kwargs):
do_something_with(specific, arguments)
super(MyClass, self).foo(*args, **kwargs)
,每一个特定的多个Container
处理有什么特别的地方,但如果有默认功能,这是通用于所有Container
秒(如果没有 - - 为什么我们要使用继承?!),那么你只能在超类中定义它,并使用super
来在子类中遵循它。