pythonsuper用法_python super init 使用及注意事项

Hello ,大家好;

在Python代码中,我们会经常看到super().__init__()

本期视频,用一个简单的实例和大家分享一下:

Super().__init__()的用法,以及注意事项

以car类,创建一个electric电动车子类为例;

注意:

1, 创建子类时,父类必须包含在当前文件中,并且位于子类之前;

2, 定义子类时,必须在括号内指定父类名称;

3, __init__()接收Car实例所需的信息;self

4, super()的目的是让子类ElectricCar调用父类Car的方法__init__(),使其包含父类的所有属性;这个是因为父类得init含self;

5, python2.7 与 python3 中用法不同;

接下来,我们先看看在python3中的代码:

***********************************************************

class Car():

def __init__(self,make,model,year):

self.make = make

self.model = model

self.year = year

def get_descriptive_name(self):

long_name = str(self.year) + + self.make + + self.model

return long_name.title()

class ElectricCar(Car):

def __init__(self,make,model,year):

super().__init__(make,model,year)

my_car = ElectricCar(hongqi,X 110,2030)

print(my_car.get_descriptive_name())

***********************************************************

再看看python2.7中的super使用:

1,这个object不能忘了

2,super需要有两个参数

***********************************************************

class Car(object):

def __init__(self,make,model,year):

self.make = make

self.model = model

self.year = year

def get_descriptive_name(self):

long_name = str(self.year) + + self.make + + self.model

return long_name.title()

class ElectricCar(Car):

def __init__(self, make, model, year):

super(ElectricCar, self).__init__(make, model, year)

my_car = ElectricCar(hongqi, X 110, 2030)

print(my_car.get_descriptive_name())

***********************************************************

好的,今天这期视频就到这里,谢谢观看。【python学习心得】super init的使用及注意事项_哔哩哔哩 (゜-゜)つロ 干杯~-bilibiliwww.bilibili.com

经验分享 程序员 微信小程序 职场和发展