目录
- 一、创建和使用类
- 1.1 创建类
- 1.2 根据类创建实例
- 1.2.1访问属性
- 1.2.2 调用方法
- 1.2.3 创建多个实例
- 练习题
- 二、使用类和实例
- 2.1 创建一个类
- 2.2 给属性指定默认值
- 2.3 修改属性值
- 2.3.1 直接通过实例进行修改
- 2.3.2通过方法进行设置
- 2.2.3 通过方法对属性值进行递增
- 练习题
- 三、继承
- 3.1 子类的方法__init__ ( )
- 3.2 给自立而定义属性和方法
- 3.3 重写(overwrite)父类的方法
- 3.4 将实例用作属性
- 练习题
- 四、导入类
- 4.1 导入单个类
- 4.2 从一个模块中导入多个类
- 4.3 导入整个模块
- 4.4 导入模块中的所有类
- 4.5 使用别名
- 五、Python标准库
- 实例:random库
- 练习题
一、创建和使用类
1.1 创建类
-
class
创建类关键字,类为大写字母开头。 -
内置__init__( )方法
init方法开头和结尾都有两个下划线,旨在避免Python默认方法与普通方法发生冲突,当创建新实例时,Python会自动运行该方法。 -
self
init方法在定义时必须要包含的一个形参为self,而且必须位于形参的第一位。
Python调用这个方法来创建实例时,将自动传入实参self 。每个与实例相关联的方法调用都自动传递实参self ,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。 -
属性
在init方法中,除了self为第一个形参,还可以有其他形参来描述该类,如person类可以有name和age来进行描述,因此init方法中可以传入的参数为self、name和age3个形参,在init方法中使用self.name = name和self.age = age为两个变量赋值,并将变量关联到当前创建的实例上。 -
类中的自定义方法
这些方法在定义时也需要加上形参self。
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!")
1.2 根据类创建实例
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(f"{self.name} is sitting now!")
def roll_over(self):
print(f"{self.name} roller over!")
d = Dog('winnie', 2)
d.sit()
d.roll_over()
创建类的实例:a = Class( )
- 上述代码表示为Dog类创建一个名为d的实例(创建一条名为winnie,年龄为2的小狗。
- 遇到这行代码时,Python使用实参 ‘winnie’ 和 2 调用Dog 类的方法__init__() 。
- 方法__init__() 创建一个表示特定小狗的实例,并使用提供的值来设置属性name和age 。
1.2.1访问属性
使用实例名加点的方式调用属性。
a.value
1.2.2 调用方法
使用实例名加点方式调用方法。
a.method( )
1.2.3 创建多个实例
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(f"{self.name.title()} is sitting now!")
def roll_over(self):
print(f"{self.name.title()} roller over!")
dog1 = Dog('winnie', 2)
dog2 = Dog('jack',6)
dog1.sit()
dog2.sit()
练习题
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f"{self.restaurant_name.title()} serve {self.cuisine_type}.")
def open_restaurant(self):
print(f"{self.restaurant_name.title()} is opening now.")
restaurant = Restaurant('burger king', 'fast food')
restaurant.describe_restaurant()
restaurant.open_restaurant()
r1 = Restaurant('subway','sandwich')
r1.describe_restaurant()
r2 = Restaurant('the french laundry','french cuisine')
r2.describe_restaurant()
class User:
def __init__(self,first_name,last_name,age,city):
self.first_name = first_name
self.last_name = last_name
self.format_name = f"{self.first_name} {self.last_name}".title()
self.age = age
self.city = city
def describe_user(self):
print(f"{self.format_name} is {self.age} years old and is living in {self.city.title()} now!")
def greet_user(self):
print(f"{self.format_name}, good morning!")
user1 = User('winnie','ma',23,'zibo')
user1.greet_user()
user1.describe_user()
user2 = User('jack','wang',34,'chicago')
user2.greet_user()
user2.describe_user()
在该代码中创建了一个名为format_name的属性,而不是通过形参来定义的,后面会讲到如何不通过形参来定义并使用属性。
二、使用类和实例
2.1 创建一个类
创建一个汽车类,属性包括汽车的品牌、型号和出厂时间。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
my_new_car = Car('audi','a4',2019)
print(my_new_car.get_descriptive_name())
2.2 给属性指定默认值
创建实例时,有些属性无须通过形参来定义,可在方法__init__() 中为其指定默认值。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
my_new_car = Car('audi','a4',2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
在init方法中,为car类创建了一个名为odometer_reading的属性,并为其赋值为0。
2.3 修改属性值
修改属性值的方法:
- 直接通过实例进行修改
- 通过方法进行设置
- 通过方法进行递增
2.3.1 直接通过实例进行修改
直接使用实例调用该属性并且为其赋值。
2.3.2通过方法进行设置
在类中定义一个函数,使用该函数对属性值进行修改。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
my_new_car = Car('audi','a4',2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_odometer(25)
my_new_car.read_odometer()
2.2.3 通过方法对属性值进行递增
将属性递增特定的值。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
def increment_odometer(self,miles):
self.odometer_reding += miles
my_new_car = Car('audi','a4',2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_odometer(25)
my_new_car.read_odometer()
my_new_car.increment_odometer(100)
my_new_car.read_odometer()
练习题
9-4
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f"{self.restaurant_name.title()} serve {self.cuisine_type}.")
def open_restaurant(self):
print(f"{self.restaurant_name.title()} is opening now.")
def number_served_restaurant(self):
print(f"This is restaurant can serve for {self.number_served} people.")
def set_number_served(self,n):
self.number_served = n
def increment_number_served(self,m):
self.number_served += m
restaurant = Restaurant('burger king', 'fast food')
restaurant.number_served_restaurant()
restaurant.number_served = 20
restaurant.number_served_restaurant()
restaurant.set_number_served(50)
restaurant.number_served_restaurant()
restaurant.increment_number_served(30)
restaurant.number_served_restaurant()
9-5
class User:
def __init__(self,first_name,last_name,age,city):
self.first_name = first_name
self.last_name = last_name
self.format_name = f"{self.first_name} {self.last_name}".title()
self.age = age
self.city = city
self.login_attempts = 0
def describe_user(self):
print(f"{self.format_name} is {self.age} years old and is living in {self.city.title()} now!")
def greet_user(self):
print(f"{self.format_name}, good morning!")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
user1 = User('winnie','ma',23,'zibo')
print(user1.login_attempts)
for i in range(1,11):
user1.increment_login_attempts()
print(user1.login_attempts)
user1.reset_login_attempts()
print(user1.login_attempts)
三、继承
如果要编写的类是另一个现成类的特殊版本,可使用继承 。
- 一个类继承另一个类时,将自动获得另一个类的所有属性和方法。
原有的类称为父类(超类) ,而新类称为子类 。
- 子类继承了父类的所有属性和方法,同时还可以定义自己的属性和方法。
3.1 子类的方法__init__ ( )
-
编写子类时,通常要调用父类的方法__init__( ) 来初始化在父类__init__( ) 方法中定义的所有属性,从而让子类包含这些属性。
-
定义子类时,必须在圆括号内指定父类的名称。
-
super ( ) :一个特殊函数,能够调用父类的方法,在子类init方法中使用super方法调用父类中的init方法,从而使得子类可以获得父类中的所定义的所有属性。
-
子类必须定义在父类下面。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
print(long_name.title())
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
def increment_odometer(self,miles):
self.odometer_reding += miles
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
my_tesla = ElectricCar('tesla','model s',2020)
my_tesla.get_descriptive_name()
此时定义了一个父类为Car子类为ElectriCar的车实例my_tesla,在子类中使用super方法继承父类的init方法,使得子类有了父类的所有属性和方法。
3.2 给自立而定义属性和方法
让一个类继承另一个类后,可以继续添加子类所需的新属性和新方法。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
print(long_name.title())
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
def increment_odometer(self,miles):
self.odometer_reding += miles
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery_size = 75
def describe_battery(self):
print(f"This car has a {self.battery_size}-kWh battery.")
my_tesla = ElectricCar('tesla','model s',2020)
my_tesla.get_descriptive_name()
my_tesla.describe_battery()
代码在子类init方法中为子类电车类添加了一个特有属性:电池容量(self.battery_size),并且添加了一个新方法:显示电池容量。
3.3 重写(overwrite)父类的方法
在子类中定义一个与想要重写的父类方法同名的方法,这样可以对父类中的这个方法进行覆盖,使用子类实例调用该方法时,Python不会考虑父类中的这个方法,而是只关注在子类中重写后的方法。
我们可以重写父类中的get_descriptive_name方法,然后进行调用。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
print(long_name.title())
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
def increment_odometer(self,miles):
self.odometer_reding += miles
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery_size = 75
def describe_battery(self):
print(f"This car has a {self.battery_size}-kWh battery.")
def get_descriptive_name(self):
long_name = f"This is an electric car : {self.year} {self.make} {self.model}"
print(long_name.title())
my_tesla = ElectricCar('tesla','model s',2020)
my_tesla.get_descriptive_name()
my_tesla.describe_battery()
可以看到调用后显示的是重写后的内容。
3.4 将实例用作属性
可以将一个类的实例用作另一个类的属性。
在代码中新建一个电池类,然后在电车类的init方法中引用这个类的实例作为属性。
下面在使用电车类的属性battery时,可以进一步调用battery类中的方法。
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
#创建一个属性并为其赋一个默认值
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
print(long_name.title())
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
def increment_odometer(self,miles):
self.odometer_reding += miles
class Battery:
def __init__(self,battery_size=75):
self.battery_size = battery_size
def describe_battery(self):
print(f"This car has a {self.battery_size}-kWh battery.")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
def get_descriptive_name(self):
long_name = f"This is an electric car : {self.year} {self.make} {self.model}"
print(long_name.title())
my_tesla = ElectricCar('tesla','model s',2020)
my_tesla.get_descriptive_name()
my_tesla.battery.describe_battery()
练习题
9-6
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f"{self.restaurant_name.title()} serve {self.cuisine_type}.")
def open_restaurant(self):
print(f"{self.restaurant_name.title()} is opening now.")
def number_served_restaurant(self):
print(f"This is restaurant can serve for {self.number_served} people.")
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = ['strawberry','chocolate','vanilla']
def show_flavors(self):
for flavor in self.flavors:
print(f"{flavor.title()}")
iceCreamStand = IceCreamStand('gelato','icecream')
iceCreamStand.describe_restaurant()
iceCreamStand.show_flavors()
9-7
class User:
def __init__(self,first_name,last_name,age,city):
self.first_name = first_name
self.last_name = last_name
self.format_name = f"{self.first_name} {self.last_name}".title()
self.age = age
self.city = city
self.login_attempts = 0
def describe_user(self):
print(f"{self.format_name} is {self.age} years old and is living in {self.city.title()} now!")
def greet_user(self):
print(f"{self.format_name}, good morning!")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self,first_name,last_name,age,city):
super().__init__(first_name,last_name,age,city)
self.privileges = []
def add_privileges(self,privilege):
self.privileges.append(privilege)
def show_privileges(self):
print(self.privileges)
admin = Admin('winnie','ma',22,'zibo')
admin.describe_user()
admin.add_privileges('can add post')
admin.add_privileges('can delete post')
admin.add_privileges("can ban user")
admin.show_privileges()
9-8
class User:
def __init__(self,first_name,last_name,age,city):
self.first_name = first_name
self.last_name = last_name
self.format_name = f"{self.first_name} {self.last_name}".title()
self.age = age
self.city = city
self.login_attempts = 0
def describe_user(self):
print(f"{self.format_name} is {self.age} years old and is living in {self.city.title()} now!")
def greet_user(self):
print(f"{self.format_name}, good morning!")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Privileges:
def __init__(self,privileges=[]):
self.privileges = privileges
def add_privileges(self,privilege):
self.privileges.append(privilege)
def show_privileges(self):
print(self.privileges)
class Admin(User):
def __init__(self,first_name,last_name,age,city):
super().__init__(first_name,last_name,age,city)
self.privileges = Privileges()
admin = Admin('winnie','ma',22,'zibo')
admin.describe_user()
admin.privileges.add_privileges('can add post')
admin.privileges.add_privileges('can delete post')
admin.privileges.show_privileges()
9-9
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reding = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
print(long_name.title())
def read_odometer(self):
print(f"This car has {self.odometer_reding} miles on it.")
def update_odometer(self,mileage):
self.odometer_reding = mileage
def increment_odometer(self,miles):
self.odometer_reding += miles
class Battery:
def __init__(self,battery_size=75):
self.battery_size = battery_size
def get_range(self):
if self.battery_size == 75:
range = 260
else:
range = 315
print(f"This car can go about {range} miles on a full charge.")
def upgrade_battery(self):
if self.battery_size != 100:
self.battery_size = 100
def describe_battery(self):
print(f"This car has a {self.battery_size}-kWh battery.")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
def get_descriptive_name(self):
long_name = f"This is an electric car : {self.year} {self.make} {self.model}"
print(long_name.title())
car = ElectricCar('tesla','t4',2022)
car.battery.get_range()
car.battery.upgrade_battery()
car.battery.get_range()
四、导入类
4.1 导入单个类
把Car类存放在car.py文件中,然后再main.py中调用该类。
from car import Car
4.2 从一个模块中导入多个类
把Battery类和ElectricCar类也存放进car.py文件里,然后再main.py中调用这两个类。
from car import Car,ElectricCar
4.3 导入整个模块
import car
my_car = car.Car(...)
访问类时需要加上模块名:
module_name.ClassName
4.4 导入模块中的所有类
from car import *
访问类时需要加上模块名:
module_name.ClassName
4.5 使用别名
from electric_car import ElectricCar as EC
my_tesla = EC('tesla', 'roadster', 2019)
五、Python标准库
实例:random库
使用import来导入Python标准库中的函数和类,这里使用random模块来进行实例。
-
randint( ) 方法:将连个整数作为参数,随机返回一个位于这两个整数之间的整数。
-
choice( )方法:将一个列表或者元组作为参数,随机返回其中的一个元素。
下面代码将实现:
- 随机产生一个1和6之间的整数
- 在玩家列表中随机返回一个玩家
from random import *
print(randint(1,6))
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(choice(players))
练习题
9-13
from random import *
class Die:
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
print(f"{self.sides} sides: You get {randint(1, self.sides)} this time!")
die = Die()
for i in range(1,11):
die.roll_die()
die1 = Die(10)
for i in range(1,11):
die1.roll_die()
die2 = Die(20)
for i in range(1,11):
die2.roll_die()
9-14
from random import *
ticket = [15,2,96,451,3,12,43,890,3,55,'a','g','c','y','w']
right_choices = []
while True:
flag = True
c = choice(ticket)
for right_choice in right_choices:
if c == right_choice:
flag = False
break
if flag:
right_choices.append(c)
if len(right_choices) == 4:
break
print(f"If you get the list of {right_choices}, you win the prize!")