Python之类、类的继承

1>创建了一个汽车类

在Python2.7X中在类定义中需要添加object,但是在Python3X中是要省略不要的
init()方法是在创建类实例car时自动调用的,且自动传入实参self。
!每个与类相关联的方法都自动传递实参self,它是一个指向实参本身的引用,
让示例能够访问类中的方法和属性。
!以self为前缀的变量可以供类中的所有方法使用,
!并且还可以通过类中的任何示例来访问这些变量。类似与C、C++的类中的public变量。
!设置默认值self.odermeter_reader=0

class  Car(object):
    def __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odermeter_reader=0

    def get_descriptive_name(self):
        long_name=str(self.year)+' '+self.make+' '+self.model
        return long_name


my_new_car=Car('audi','a4','2017')
print(my_new_car.get_descriptive_name())```
  #####2>继承
一个类继承另外一个类时,自动获得被继承类(即父类)的所有方法和属性。同时
子类还可以定义自己的属性和方法。
且父类必须在同一个文件中,或者导入到该项目中。
在Python3.5的版本中只需要
`super().__init__(make,model,year)`
Python2.7的创建继承的方法:

class ElectricCar(Car):
def init(self,make,model,year,battery=40):
super(ElectricCar,self).init(make,model,year)
self.battery_size=battery

def describe_battery(self):
    print("This car has a "+str(self.battery_size)+"-kwh battery.")
!super()方法是将父类和子类关联起来的特殊函数,使得子类包含父类的所有特性。
!在 __init__()函数还添加了子类自己的属性,
  #####3>改写父类的方法
如上的__init__(),当子类调用和父类的同名方法时,,首先调用子类里面的被重写的方法,忽略父类的方法。
#####4>用实例当做属性

class Batery(object):
def init(self,battery_size=90):
self.battery_size=battery_size

def describe_battery(self):
    print("This car has a "+str(self.battery_size)+"-kwh battery.")

class ElectricCar(Car):
def init(self,make,model,year,battery=40):
super(ElectricCar,self).init(make,model,year)
self.battery=Batery()

调用ElectricCar

my_new_car2=ElectricCar(‘audi’,’a4′,’2017′)
print(my_new_car2.get_descriptive_name())
my_new_car2.battery.describe_battery()


    原文作者:exmexm
    原文地址: https://www.jianshu.com/p/5ea52b44acfd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞