擅长:python、mysql、java
<p>只要<code>__init__()</code>签名兼容,就可以使用实例的类型而不是显式类型。在</p>
<pre><code>class Parent(object):
def __str__(self):
return 'I am a Parent'
def reproduce(self):
# do stuff common to all subclasses.
print('parent reproduction')
# then return an instance of the caller's type
return type(self)()
class Child(Parent):
def __str__(self):
return 'I am a Child'
def reproduce(self):
# do stuff specific to Child.
print('child reproduction')
# call the parent's method but it will return a
# Child object
return super(Child, self).reproduce()
print(Parent().reproduce())
parent reproduction
I am a Parent
print(Child().reproduce())
child reproduction
parent reproduction
I am a child
</code></pre>