我希望有一个包含在其他方法中调用的方法的类,但我希望这些方法是可重写的,并默认传递。有没有办法(很好地)做到这一点?
编辑:我特别感兴趣的是如何准确地覆盖这些方法。我试过def setup(self): ...,game.setup = setup。这在某种程度上是可行的,但它不能与"self“参数一起正常工作,抛出setup() missing 1 required positional argument: 'self'
编辑2:我已经意识到我应该继承Game的子类,并重写子类中的方法。我不知道为什么花了这么长时间。
为了防止我的话很愚蠢和令人困惑,下面是一些代码:
class Game(threading.Thread):
def update(self):
pygame.display.update()
self.screen.fill(self.fillcolour)
def setup(self):
"""Placeholder for setup"""
pass
def frame(self):
"""Placeholder for frame"""
pass
def handleInputs(self):
"""Placeholder for input handling"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
def run(self):
self.setup()
while True:
if self.FRAMERATE:
self.clock.tick(self.FRAMERATE)
self.frame()
self.update()
self.handleInputs()发布于 2013-03-10 01:32:12
这就是所谓的Template Method Pattern,你的代码就没问题了。
不过,您可能希望为每个事件调用一个可覆盖的方法,而不是覆盖整个handleInputs (否则每次都必须重新实现循环)。
class Game(threading.Thread):
def update(self):
pygame.display.update()
self.screen.fill(self.fillcolour)
def setup(self):
"""Placeholder for setup"""
pass
def frame(self):
"""Placeholder for frame"""
pass
def handleEvent(self, event):
"""Placeholder for input handling"""
pass
def handleInputs(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
self.handleEvent(event)
def run(self):
self.setup()
while True:
if self.FRAMERATE:
self.clock.tick(self.FRAMERATE)
self.frame()
self.update()
self.handleInputs()发布于 2013-03-10 01:30:19
我想你可以这样做:
class Whatever(object):
def _placeholder(self,*args,**kwargs):
"""
This function does nothing, but in a subclass,
it could be useful ...
"""
return
setup = _placeholder
frame = _placeholder
...这至少减少了样板代码...
https://stackoverflow.com/questions/15313665
复制相似问题