1、类的定义
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is sitting!")
def roll_over(self):
print(self.name.title() + " is rolling!")
构造方法__init__(),里面的方法都要带self。
类中的每个属性必须有初始值,哪怕是0或者空字符串。
2、创建实例
my_dog = Dog("kity", 3)
my_dog.sit()
3、使用实例
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it")
def update_odometer(self, mileage):
self.odometer_reading = mileage
class Battery():
def __init__(self, battery_size = 70):
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):
super().__init__(make, model, year)
self.battery = Battery(100)
my_car = Car("audi", "a4", 3)
my_car.read_odometer()
my_car.update_odometer(356)
my_car.read_odometer()
my_car.odometer_reading = 200
my_car.read_odometer()
my_elc_car = ElectricCar("tesla", "model s", 1)
my_elc_car.battery.describe_battery()
读取实例的值,修改实例的值
4、继承
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery_size = 100
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kwh battery.")
创建子类,父类必须在子类的前方。定义子类的时候,父类名称写入子类的括号中。super()方法让子父类关联起来。
可以重写父类的方法。
类的属性还可以是一个类:
self.battery = Battery()
可以从模块引入类:from module_name import class_name,如果引入整个模块就使用import module_name