从子类中初始化父类,以便父类属性可用于创建的子类实例是否是一种好的做法? 这样做有替代方案或最佳做法吗?
举个例子:
class Animal(object):
def __init__(self, name, weight, cute=False, image=None):
#Instantiation attributes
self.name = name
self.weight = weight
self.cute = cute
self.image = image
#Attributes common to all animals
self.extinct = False
def get_animal_stats(self):
print arbitrary_animal_stat
class Dog(Animal):
def __init__(self, name, weight):
Animal.__init__(self, name, weight, cute=True, image="dog.com")
#Additional attributes unique to dogs
self.number_legs = 4
self.teeth = True
def make_noise(self):
print "Bark!"
据我了解,在子类初始化时不初始化父类,子类对象只能访问自己的属性(即number_legs和teeth,以及make_noise)而不能访问父类的属性或方法(即excitent和 get_animal_stats)。
我发现自己为预定义对象编写了许多小类,但必须用子对象初始化父对象。通过这种方式,我可以即时创建一个简单的 Animal 或通过 Dog 子类创建一个更具描述性的 Animal。
从子类实例访问父属性和方法的正确方法是什么?我是否误解了子类的使用?
请您参考如下方法:
不仅可以接受,您几乎应该总是调用父类的构造函数。你不会这样做的唯一原因是如果你
- 绝对确定在父类中永远不会定义对象运行所必需的任何初始化代码,并且
- 您想显式覆盖父类的初始化行为。
对于新样式类(那些继承自对象的类),最好使用 super() 因为它会处理多重继承情况下的解析顺序。在 Python 2.7 中,使用:
class ParentFooA(GrandparentFoo):
def __init__(self):
some_important_initialization_code()
class ChildFoo(ParentFoo):
def __init__(self):
super(ChildFoo, self).__init__()
请注意,另一个不错的属性是您不必在 ChildFoo 中的任何地方使用名称 ParentFoo except 当您定义继承时 (例如,在 class ChildFoo(...) 行中。它也适用于其他方法:
class ChildFoo(ParentFoo):
...
def do_buzz(self):
super(ChildFoo, self).do_buzz()
super() 不 对旧式类(即不从 object 继承的类)起作用。 这意味着对于许多标准库,您仍然必须显式调用父类的构造函数。所以在这种情况下:
class OldStyleParent:
def __init__(self):
...
您必须在 __init__() 中显式调用 OldStyleParent.__init__()。
在 Python 3 中,super 的语法很简单:
class ChildFooInPython3(ParentFoo):
def __init__(self):
super().__init__()
