创建一个简单的类
根据Dog类创建的每个实列都将存储名字和年龄。我们赋予了每条小狗蹲下(sit())和打滚(roll_over())的能力:
1 class Dog(): 2 """一次模拟小狗的简单尝试""" 3 def __init__(self, name, age): 4 """初始化属性name和age""" 5 self.name = name 6 self.age = age 7 def sit(self): 8 """模拟小狗被命令时蹲下""" 9 print(self.name.title() + "now is sitting.") 10 def roll_over(self): 11 """模拟小狗被命令时打滚""" 12 print(self.name.title() + "rolled over!") 13 my_dog = Dog('tom','3') 14 print("my dog name is " + my_dog.name.title() )
根据约定,在Python中,首字母大写的名称指的是类:类中的函数称为
方法
方法__init__(),开头和末尾都有2个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称的冲突。
我们将方法__init__()定义成了包含三个形参: self、 name和age。在这个方法的定义中,参self必不可少,还必须位于其他形参的前面。为何必须在方法定义中包含形参self呢?因为Python调用这个__init__()方法来创建Dog实例时,将自动传入实参self。 两个变量self_name和self_age都有前缀self,以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实列来访问这些变量。像这样可通过实例访问的变量称为属性。
在python2.X中,如果创建类需要在括号后面加上(object)。
访问属性
继续上面的例子,方法__init__()创建一个表示特定小狗的示例,并使用我们提供的值来设置属性name和age,方法__init__()并未显式地包含return语句,但python自动返回一个表示这条小狗的示例。我们将这个示例存储在变量my_dog中。
class Dog(): """一次模拟小狗的简单尝试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title() + " now is sitting.") def roll_over(self): """模拟小狗被命令时打滚""" print(self.name.title() + " rolled over!") my_dog = Dog('tom',3) print(my_dog.name) print(my_dog.age) #运行结果 tom 3
调用方法
class Dog(): """一次模拟小狗的简单尝试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title() + " now is sitting.") def roll_over(self): """模拟小狗被命令时打滚""" print(self.name.title() + " rolled over!") my_dog = Dog('tom',3) my_dog.sit() my_dog.roll_over() #运行结果 Tom now is sitting. Tom rolled over!
根据Dog类创建实例后,就可以使用句点表示来调用Dog来定义的任何方法
创建多个实例
class Dog(): """一次模拟小狗的简单尝试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title() + " now is sitting.") def roll_over(self): """模拟小狗被命令时打滚""" print(self.name.title() + " rolled over!") my_dog = Dog('tom',3) your_dog = Dog('Mei',2) print("My dog name is " + my_dog.name.title()) print("Your dog name is " + your_dog.name.title()) #运行结果 My dog name is Tom Your dog name is Mei
可按需求根据类创建任意数量的实例。
使用类和实例
给属性指定默认值
类中的每个属性都必须有初始值,哪怕这个值是0或空字符串,在有些情况下,如设置默认值时,在方法__init__()内指定这种初始值时可以的没如果你对某个属性这样做了,就无需包含为他提供初始化的形参。
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """汽车的初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 100 def get_descri_name(self): """描述汽车""" long_name = str(self.year) + ' ' + self.model + ' ' + self.make return long_name my_car = Car('audi', 'a4', '2017') print(my_car.model) print(my_car.get_descri_name()) #运行结果 a4 2017 a4 audi
直接修改属性的值
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """汽车的初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 100 def get_descri_name(self): """描述汽车""" long_name = str(self.year) + ' ' + self.model + ' ' + self.make return long_name my_car = Car('audi', 'a4', '2017') print(my_car.get_descri_name()) my_car.year = 2016 print(my_car.get_descri_name()) #运行结果 2017 a4 audi 2016 a4 audi
通过方法修改
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """汽车的初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 100 def get_descri_name(self): """描述汽车""" long_name = str(self.year) + ' ' + self.model + ' ' + self.make return long_name def update(self, mile): """更新里程值""" if mile > self.odometer_reading: self.odometer_reading = mile else: print("You can't roll back an odometer") def increment_odometer(self,mile): """增加里程""" self.odometer_reading += mile def read_odometer(self): """打印汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") my_car = Car('audi', 'a4', '2017') my_car.read_odometer() my_car.odometer_reading = 10 #直接修改里程值 my_car.update(200) #通过方法修改里程 my_car.read_odometer() my_car.increment_odometer(10) my_car.read_odometer() #运行结果 This car has 100 miles on it. This car has 200 miles on it. This car has 210 miles on it.
继承
如果我们想再一个class继承另一个类的属性,可以在类后面括号中加入类的名称,举例如下:
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """汽车的初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 100 def get_descri_name(self): """描述汽车""" long_name = str(self.year) + ' ' + self.model + ' ' + self.make return long_name def update(self, mile): """更新里程值""" if mile > self.odometer_reading: self.odometer_reading = mile else: print("You can't roll back an odometer") def increment_odometer(self,mile): """增加里程""" self.odometer_reading += mile def read_odometer(self): """打印汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") 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_descri_name()) #运行结果 2016 model s tesla
为了继承父类的属性,还需要加入一个特殊的函数super(),帮助python将夫类和子类关联起来。
在python2.X中,类supper的格式如下:
supper(Eletric,self).__init__(make, model, year)
给子类定义属性和方法
让一个类继承另一个类后,可添加区分子类和父类所属的新属性和新方法。
将实例用作属性
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """汽车的初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 100 def get_descri_name(self): """描述汽车""" long_name = str(self.year) + ' ' + self.model + ' ' + self.make return long_name def update(self, mile): """更新里程值""" if mile > self.odometer_reading: self.odometer_reading = mile else: print("You can't roll back an odometer") def increment_odometer(self,mile): """增加里程""" self.odometer_reading += mile def read_odometer(self): """打印汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") 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() my_tesla = ElectricCar('tesla', 'model s', '2016') print(my_tesla.get_descri_name()) my_tesla.battery.describe_battery() #运行结果 2016 model s tesla This car has a 70-kwh battery.
导入类
导入单个或者多个类
一个文件car.py
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): """汽车的初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 100 def get_descri_name(self): """描述汽车""" long_name = str(self.year) + ' ' + self.model + ' ' + self.make return long_name def update(self, mile): """更新里程值""" if mile > self.odometer_reading: self.odometer_reading = mile else: print("You can't roll back an odometer") def increment_odometer(self,mile): """增加里程""" self.odometer_reading += mile def read_odometer(self): """打印汽车的里程""" print("This car has " + str(self.odometer_reading) + " miles on it.") 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()
创建另一个文件my_car.py,导入一个类
from car import Car my_car = Car('audi', 'a4', '2017')
一个模块中可以存储多个类,所以可以一次导入多个类
from car import Car,Battery,ElectricCar my_tesla = ElectricCar('tesla', 'model s', '2016') print(my_tesla.get_descri_name()) my_tesla.battery.describe_battery()
导入整个模块
import car #导入整个模块的时候,需要使用句点表示法访问需要的类 my_tesla = car.ElectricCar('tesla', 'model s', '2016') print(my_tesla.battery)
导入所有类
from car import * #导入所有的类