【问题标题】:Can inheritance be implemented into affecting methods in subclasses?可以将继承实现到影响子类中的方法吗?
【发布时间】:2016-01-22 20:30:43
【问题描述】:

我目前正在开发一个 pygame 游戏。有两个班。一个是质量,另一个是球。 Ball 是 Mass 的子类。

我创建的每个对象都将继承自 Mass。它是一个基类。在我创建的对象中,我设计了move 方法来实现重力。但我想要完成的事情是在Mass 类中提供这种重力(基本上是方法中定义的负加速度值)。因此,通过在所有 move 方法中进行编码来避免重复。

所以我应该在Mass 中定义另一个move 方法。子类的方法会覆盖它吗?到目前为止,我试图找到解决方案的尝试都失败了。所以我不是要你为我写代码,我恳请你能否指出正确的方向,也许告诉我应该探索什么,我将不胜感激。

class Mass(object):
    # The base class

class Ball(Mass):

    def __init__(self, surface, radius, color, starting_pos):
        self.radius = radius
        self.color = color
        self.starting_pos = starting_pos
        self.surface = surface

    def move(self):
        # Keyboard handlers

    def draw(self):
        pygame.draw.circle(self.surface, self.color, (self.starting_pos), self.radius )   

【问题讨论】:

    标签: python python-2.7 inheritance pygame


    【解决方案1】:

    是的,在覆盖它的子类中对 move() 的调用默认不会调用 Mass 的调用。您仍然可以通过它的子类实现内部显式调用父方法。

    class Ball(Mass):
      #...
      def move(self):
        Mass.move(self)
        #...
    

    当您调用ballInstance.move() 时,您在这里所做的只是获取未绑定的Mass.move 方法并使用Ball 实例ballInstance 调用它。这是查看显式 self 参数的好方法。

    【讨论】:

    • 或者,更一般地说,super 可用于调用对象超类的方法。
    • 那么这种调用方法的方式其实就是复制那个方法的源代码?是一样的吗?
    • 无源代码副本。这是对Mass.move 方法的显式调用。
    • 我猜你可以这样想,但它们是不同的方法。这只是访问被覆盖方法的一种方式。
    • 我可以在调用该方法后添加更多功能对吗?
    【解决方案2】:

    如果重力会在所有质量对象之间共享,为什么它不是一个类属性?您也可以从子类中调用Mass.move

    class Mass(object):
        gravity = -9.8
        def move(self):
           #generic movement
        # The base class
    
    class Ball(Mass):
        ...
        def move(self):
            Mass.move(self)#run the one defined in Mass
            #then do anything extra
            print(self.gravity)
    

    这样常量在所有对象之间共享,任何子类仍然可以依赖于 Mass 中的公共代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2011-09-14
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      相关资源
      最近更新 更多