创建类和实例
# 创建Dog类
class Dog():
"一次模拟小狗的简单尝试"
def __init__(self,name,age):
"初始化属性name和age"
self.name = name
self.age = age
def sit(self):
"模拟小狗被命令时蹲下"
print(self.name.title() + " is now sitting.")
def roll_over(self):
"模拟小狗被命令时打滚"
print(self.name.title() + " rolled over.")
# 创建实例
my_dog = Dog("willie", 6)
my_dog.sit()
my_dog.roll_over()
Willie is now sitting.
Willie rolled over.
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
# 创建实例
my_new_car = Car("audi", "a4", 2016)
print(my_new_car.get_descriptive_name())
2016 Audi A4
给属性指定默认值
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
# 创建实例
my_new_car = Car("audi", "a4", 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
修改属性的值
1、直接修改属性的值
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
# 创建实例
my_new_car = Car("audi", "a4", 2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23 # 直接修改参数
my_new_car.read_odometer()
2016 Audi A4
This car has 23 miles on it.
2、通过方法修改属性值
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage): # 通过方法修改属性值
self.odometer_reading = mileage
# 创建实例
my_new_car = Car("audi", "a4", 2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer()
2016 Audi A4
This car has 23 miles on it.
可对update_odometer()函数进行拓展,防止任何人将里程数往回调
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage): # 增设判断条件,防止回调
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer.")
# 创建实例
my_new_car = Car("audi", "a4", 2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(-1)
my_new_car.read_odometer()
2016 Audi A4
You can't roll back an odometer.
This car has 0 miles on it.
3、通过方法对属性的值进行递增
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
def increment_odometer(self, miles): # 增设判断条件,防止回调
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer.")
# 创建实例
my_new_car = Car("audi", "a4", 2016)
print(my_new_car.get_descriptive_name())
my_new_car.increment_odometer(1)
my_new_car.read_odometer()
my_new_car.increment_odometer(-1)
my_new_car.read_odometer()
2016 Audi A4
This car has 1 miles on it.
You can't roll back an odometer.
This car has 1 miles on it.
继承
编写类时,并非总是要从空白开始。若编写的类是另一个类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的属性和方法;原有的类称为父类,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
def increment_odometer(self, miles): # 增设判断条件,防止回调
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer.")
# 创建子类
class ElectricCar(Car):
"电动汽车的独特之处"
def __init__(self, make, model, year):
"初始化父类的属性"
super().__init__(make, model, year)
# 创建实例
my_tesla = ElectricCar("tesla", "model s", 2016)
print(my_tesla.get_descriptive_name())
2016 Tesla Model S
创建子类时,父类必须包含在当前的文件中,且位于子类的前面。定义子类时,必须在括号内指定父类的名称。方法__init__()接受创建Car类实例所需的信息。super()是一个特殊的函数,帮助Python将父类和子类关联起来。子类中的super()此行代码让Python调用子类的父类的方法__init__(),让子类包含父类所有的属性。父类也称为超类(superclass),名称super()因此得名。
给子类定义属性和方法
让一个类继承另一个类后,可添加区分子类和父类所需的新属性和方法。
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
def increment_odometer(self, miles): # 增设判断条件,防止回调
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer.")
# 创建子类
class ElectricCar(Car):
"电动汽车的独特之处"
def __init__(self, make, model, year):
"初始化父类的属性,再初始化电动汽车特有的属性"
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"打印一条描述电瓶容量的消息"
print("This car has a " + str(self.battery_size) + "-kwh battery.")
# 创建实例
my_tesla = ElectricCar("tesla", "model s", 2016)
my_tesla.describe_battery()
This car has a 70-kwh battery.
重写父类
对于父类的方法,只要它不符合子类模拟的实物的行为,都可以对其进行重写。可在子类中定义一个同样的方法,及它和重写的父类的方法同名。Python将不会考虑父类的方法,而只关注子类中定义的相应的方法。即使用继承时,可让子类保留从弗雷那里继承而来的精华,并剔除不需要的糟粕。
将实例用作属性
# 创建Car类
class Car():
"一次模拟汽车的简单尝试"
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # 指定里程表读数默认值
def get_descriptive_name(self):
"返回整洁的描述性信息"
long_time = str(self.year) + " " + self.make + " " + self.model
return long_time.title()
def read_odometer(self):
"打印一条指出汽车里程的消息"
print("This car has " + str(self.odometer_reading) + " miles on it.")
def increment_odometer(self, miles): # 增设判断条件,防止回调
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer.")
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() #属性sel.battery承接了新类Battery,Battery是一个新的实例
# 创建实例
my_tesla = ElectricCar("tesla", "model s", 2016)
my_tesla.battery.battery_size = 80 # 重新定义battery_size
my_tesla.battery.describe_battery()
This car has a 80-kwh battery.
导入类
导入单个类:from model_name import class_name,如from car import Car
可在一个模块中存储多个类,如上
可从一个模块中导入多个类:from model_name import class_0, class_1, class_2
可导入整个模块:import model_name 或 from model_name import *
可在一个模块中导入另一个模块
类编码风格
1、类名应该采用驼峰命名法,即将类名中的每个单词首字母都大写,而不使用下划线。实例名和模块名都采用小写格式,并在单词之间加上下划线。
2、对于每个类,都应紧跟在类定义后面包含一个文档字符串。这种文档字符串简要的描述类的功能,并遵循编写函数的文档字符串时采用的格式约定。每个模块也都应包含一个文档字符串,对其中的类可用于做什么进行描述。
3、可使用空行来组织代码,但不要滥用。在类中,可使用一个空行来分隔方法;而在模块中,可使用两个空行来分隔类。
4、需要同时导入标准库中的模块和自写的模块是,先导入标准库,再添加一个空行,再导入自写的模块。(让人更易明白各个模块来自于何方)