类中的函数称为方法 ;
class Dog():
def init(self, name, age):
定义类 方法init() 是一个特殊的方法,每当你根
据Dog 类创建新实例时,Python都会自动运行它。
Python调用这个init() 方法来创建Dog 实例时,将自动传入实参self 。每个与类相关联的方法调用都自动传递实参self ,它是一个指向实例本身
的引用,让实例能够访问类中的属性和方法。
class Car():
def __init__(self, make, modle, year):
self.make = make
self.modle = modle
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.modle
return long_name.title()
my_new_car = Car('audi', 'a4', 2016)
print (my_new_car.get_descriptive_name())
这里创建并调用了一个类
继承
python3的继承
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
python2的继承
class Car(object):
。。。。。。
class ElectriCar(Car):
def __init__(self,make,model,year):
super(ElectriCar,self).__init__(make,model,year)
重写父类的方法:在子类中重定义就会调用子类的方法不去调用父类的方法
生成ElectricCar的时候会调用 init 函数因此现在每个ElectricCar 实例都包含一个自动创建的Battery 实例。
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
.......
my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.battery.describe_battery()
导入类
car是文件Car是文件中的类
from car import Car
继承的类也同样可以
from car import ElectricCar
导入多个类
from car import Car, ElectricCar