实例化:根据类来创建对象
9.1 创建Dog实例
class Dog:
def __init__(self,name,age):
self.name = name,
self.age = age
def sit(self):
print(f"{self.name} is now sitting")
def roll_over(self):
print(f"{self.name} rolled over")
my_dog = Dog('小花',17) #实例化类
my_dog.sit() #调用方法 sit ()
my_dog.roll_over() #调用方法 roll_over ()
9.1.1 使用类和实例
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def get_describe_name(self):
long_name =f"{self.make,self.model,self.year}"
return long_name.title()
car = Car('AUDI','a4',2019)
print(car.get_describe_name())
输出:
('Audi', 'A4', 2019)
9.2 给属性指定默认值
class Car:
def __init__(self):
self.year =12
def get_year(self):
print(f"This car is {self.year}")
car = Car()
car.get_year()
输出:This car is 12
9.2.1 修改属性的值
car.year =13
car.get_year()
9.2.2 通过方法修改属性的值
class Car:
def update_odometer(self,mileage):
self.odometer_reading = mileage
print(f"公里数为 {self.odometer_reading}")
car = Car()
car.update_odometer(20)
输出:
公里数为 20
继承 关键字 super()
9.3
#定义父类 Car
class Car:
#定义父类属性 make,model,year,odometer_reading=0
def __init__(self,make,model,year):
self.make = make,
self.model = model,
self.year = year,
self.odometer_reading =0
#定义获取属性 make,model,year 的方法
def get_descriptive_name(self):
long_name =f"{self.make}{self.model}{self.year}"
return long_name.title()
#定义获取属性 odometer_reading=0 的方法
def read_odometer(self):
print(f'Thid car has {self.odometer_reading} miles on it')
#修改父类属性 odometer_reading
def update_odometer(self,mileage):
if mileage >=self.odometer_reading:
self.odometer_reading == mileage
else:
print("You can not roll back an odometer")
def increment_odometer(self,miles):
self.odometer_reading += miles
#定义子类 ElectricCar
class ElectricCar(Car):
def __init__(self,make,model,year):
#继承 父类属性
super().__init__(make,model,year)
#实例化子类
my_tesla = ElectricCar('tesla','model s',2019)
#调用父类获取属性 get_descriptive_name 方法
print(my_tesla.get_descriptive_name())
输出:
('Tesla',)('Model S',)(2019,)
9.3.1 给子类定义属性和方法
#定义子类 ElectricCar
class ElectricCar(Car):
def __init__(self,make,model,year):
#继承 父类属性
super().__init__(make,model,year)
self.buttery_size =75
def describe_buttery_size(self):
print(f"This car has a {self.buttery_size} kwh battery")
#实例化子类
my_tesla = ElectricCar('tesla','model s',2019)
#调用子类 describe_buttery_size 方法
my_tesla.describe_buttery_size()
#调用父类获取属性 get_descriptive_name 方法
print(my_tesla.get_descriptive_name())
输出:
This car has a 75 kwh battery
('Tesla',)('Model S',)(2019,)
9.4 重写父类方法
class ElectricCar(Car):
def fill_gas_tank(self):
print("This car does not need a gas tank")
9.4.4 将实例用作属性
self.battery = Battery() #Battery 为类名
mysla.battery.desribe_battery()
9.5 导入单个类
9.5.1 在一个模块中存储多个类
方法调用:
9.6 python 标准库
random
生成随机数:
from randomimport randint
print(randint(1,6))
choice
from randomimport choice
players =['charles','martina','michael']
first_up = choice(players)
print(first_up)