python - 在python中调用不同的方法

标签 python inheritance subclass

好的,我有以下内容:

Class OwnableObject(MobileObject):
   def __init__(self, name):
      MobileObject.__init__(self, name)
      self.owner = None # not owned

   def is_ownable(self): return True
   def is_owned(self): return self.owner

在OwnableObject上调用is_ownable方法有什么区别
并在 MobileObject 上调用 is_ownable 方法。

最佳答案

更新:根据您现在发布的代码,不可能在 MobileObject 上调用 is_ownable,因为 MobileObject 似乎没有 is_ownable 的定义。

如果是,那么区别就是 MobileObject 的定义和 OwnableObject 的定义之间的区别。我已经更新了下面的条款来说明我的意思。

如果你用 Python(或者任何语言,真的)创建一个类:

class MobileObject(object):
    def __init__(self, position):
        self.position = position
    def move(self, position):
        self.position = position
    def is_ownable(self):
        return False

然后创建一个子类:

class OwnableObject(MobileObject):
    def __init__(self, position, owner=None):
        MobileObject.__init__(self, position)
        self.owner = owner
    def is_ownable(self):
        return True
    def is_owned(self):
        return self.owner

生成的子类自动继承其父类(super class)的方法:

movable = MobileObject()
movable.is_ownable()       # returns False
movable.move(new_position) # moves movable
movable.is_owned()         # causes an error

ownable = OwnableObject()
ownable.is_ownable()       # returns True
ownable.move(new_position) # moves ownable
movable.is_owned()         # returns owner or None

如您所见,is_ownable()is_owned() 在这两个类之间是不同的——在后一种情况下,因为 is_owned() 未定义,在 movable 上调用时会导致错误。但是 move() 在两个类中的工作方式相同。

关于python - 在python中调用不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5433760/

相关文章:

c++ - 对成员模板函数的访问控制

objective-c - 调用 super block /扩展 block

class - 将 UIView 作为 SubView 添加到自定义类,UIView 的子类,Swift

Python 相当于 php 的 foreach($array as $key => &$value)

python - 从Python中的列表列表中提取槽

node.js - Node CoffeeScript 类文件和继承

swift - 在子类 : Swift and SpriteKit 中循环 Initialization 的 drain

python - 带有自定义类的 pickle

Python REPL : issuing commands in advance to execute after block

c++:类继承层次结构中指针数据成员的行为