在Python中,如何从超类创建一个子类?
发布于 2009-10-23 01:54:40
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
或者,更好的是,使用Python的内置函数super()
(请参阅Python 2/Python 3文档)可能是调用父函数进行初始化的一种稍好的方法:
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
或者,和上面一样,除了使用super()
的零参数形式,它只在类定义中工作:
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
发布于 2009-10-22 22:39:06
一个英勇的小例子:
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
class SuperManII(SuperHero): #another subclass
def getName(self):
return "Clark Kent, Jr."
if __name__ == "__main__":
sm = SuperMan()
print sm.getName()
sm2 = SuperManII()
print sm2.getName()
发布于 2009-10-22 22:28:47
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
python文档中的section on inheritance对此进行了更详细的说明
https://stackoverflow.com/questions/1607612
复制相似问题