Okay so I have the following:
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
What is the difference between invoking the is_ownable method on OwnableObject
and invoking the is_ownable method on a Mobil开发者_开发百科eObject.Update: Based on the code you have posted now, it's impossible to call is_ownable
on a MobileObject
because the MobileObject
doesn't appear to have a definition for is_ownable
.
If it does, then the difference is simply the difference between MobileObject
's definition and OwnableObject
's definition. I've updated the terms of the below to illustrate what I mean.
If you create a class in Python (or in any language, really):
class MobileObject(object):
def __init__(self, position):
self.position = position
def move(self, position):
self.position = position
def is_ownable(self):
return False
And then create a subclass:
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
The resulting subclass automatically inherits the methods of its superclass:
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
As you can see, is_ownable()
and is_owned()
differ between the two classes -- and in the latter case, since is_owned()
is not defined, it causes an error when called on movable
. But move()
works identically in both classes.
All of the methods implemented in the base class can be called on the subclass. The base implementation will be used unless you override the method in the subclass.
I suppose that it means the same thing as in any programming language that supports the object oriented paradigm:
>>> class Base:
... def ok(self):
... print 'OK'
...
>>> class SubClass(Base):
... def oops(self):
... print 'Oops'
...
>>> x = SubClass()
>>> x.ok()
OK
>>>
精彩评论