正常情况下,Python继承的写法是这样的:
class Human(object):
def __init__(self, name):
print(f'I am human, my name is {name}.')
def eat(self, something):
print(f'Eat {something}')
class Emperor(Human):
def __init__(self, name):
super().__init__(name)
print('I become an emperor.')
someone = Emperor('Zhang San')
皇帝也是人,所以实例化Emperor的时候首先需要实例化Human,因此程序输出:
> I am human, my name is Zhang San.
> I become an emperor.
皇帝怎么愿意承认自己是凡人呢?朕可是真龙天子。但是皇帝也要具备人类的姓名、父母以及吃喝拉撒的行为。有没有办法在继承这些方法的同时“掩盖”自己也是凡人的方法呢?很简单,不调用super的构造函数就行了:
class Human(object):
def __init__(self, name):
print(f'I am human, my name is {name}.')
def eat(self, something):
print(f'Eat {something}')
class Emperor(Human):
def __init__(self):
print('I become an emperor.')
someone = Emperor()
这样就一步到位,朕天生就是皇帝,朕甚至不需要凡人所必须的姓名。当然,这样编译器可能会报一个警告(这里就体现Python灵活的优势了,如果是C++和Java不构造父类可能会直接编译不过)。
|