Python编程:从入门到实践-类

  • 1、创建类

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 #dog.py
 4 class Dog():
 5   """一个模拟小狗的简单尝试"""
 6   def __init__(self,name,age):
 7     """初始化属性name和age"""
 8     self.name = name
 9     self.age = age
10   def sit(self):
11     """模拟小狗被命令时蹲下"""
12     print(self.name.title() + " is now sitting.")
13   def roll_over(self):
14     """模拟小狗被命令时打滚"""
15     print(self.name.title() + " rolled over!")

#方法__init__() :类中的函数成为方法,开头和结尾各有两个下划线,旨在避免Python默认方法与普通方法发生名字冲突。方法__init__定义三个形参self、name和age

__init__方法定义两个以self为前缀的变量self.name、self.age,以self为前缀的变量可供类中的所有方法使用。self.name = name获取存储在形参name中的值,并存储

在变量name中。然后该变量被关联到当前创建的实例。这样通过实例访问的变量成为属性。

  • 根据类创建实例

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 #dog.py
 4 class Dog():
 5   """一个模拟小狗的简单尝试"""
 6   def __init__(self,name,age):
 7     """初始化属性name和age"""
 8     self.name = name
 9     self.age = age
10   def sit(self):
11     """模拟小狗被命令时蹲下"""
12     print(self.name.title() + " is now sitting.")
13   def roll_over(self):
14     """模拟小狗被命令时打滚"""
15     print(self.name.title() + " rolled over!")
16 
17 my_dog = Dog('willie',6)
18 print("\nMy dog's name is " + my_dog.name.title() + ".")
19 print("\nMy dog's " + str(my_dog.age) + " years old.")
类实例化

#访问属性 my_dog.name

#调用方法 

my_dog.sit()
my_dog.roll_over()
  • 使用类和实例

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 class Car():
 4   """一次模拟汽车的简单尝试"""
 5   def __init__(self, make, model, year):
 6     self.make = make
 7     self.model = model
 8     self.year = year
 9   def get_descriptive_name(self):
10     """返回整洁的描述性信息"""
11     long_name = str(self.year) + ' ' + self.make + ' ' + self.model
12     return long_name.title()
13 my_new_car = Car('audi', 'a4', 2016)
14 print(my_new_car.get_descriptive_name())
  • 给属性指定默认值

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 class Car():
 4   """一次模拟汽车的简单尝试"""
 5   def __init__(self, make, model, year):
 6     self.make = make
 7     self.model = model
 8     self.year = year
 9     self.odometer_reading = 0
10   def get_descriptive_name(self):
11     """返回整洁的描述性信息"""
12     long_name = str(self.year) + ' ' + self.make + ' ' + self.model
13     return long_name.title()
14   def read_odometer(self):
15     """打印一条指出汽车里程的消息"""
16     print("This car has " + str(self.odometer_reading) + " miles on it.")
17 my_new_car = Car('audi', 'a4', 2016)
18 print(my_new_car.get_descriptive_name())
19 my_new_car.read_odometer()
给属性指定默认值
  •  修改属性的值

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 class Car():
 4   """一次模拟汽车的简单尝试"""
 5   def __init__(self, make, model, year):
 6     self.make = make
 7     self.model = model
 8     self.year = year
 9     self.odometer_reading = 0
10   def get_descriptive_name(self):
11     """返回整洁的描述性信息"""
12     long_name = str(self.year) + ' ' + self.make + ' ' + self.model
13     return long_name.title()
14   def read_odometer(self):
15     """打印一条指出汽车里程的消息"""
16     print("This car has " + str(self.odometer_reading) + " miles on it.")
17 my_new_car = Car('audi', 'a4', 2016)
18 #print(my_new_car.get_descriptive_name())
19 my_new_car.odometer_reading = 23
20 my_new_car.read_odometer()
直接修改属性的值
  • 通过方法修改属性的值

 1 #!/usr/bin/env python
 2 #-*- encoding:utf-8 -*-
 3 class Car():
 4   """一次模拟汽车的简单尝试"""
 5   def __init__(self, make, model, year):
 6     self.make = make
 7     self.model = model
 8     self.year = year
 9     self.odometer_reading = 0
10   def get_descriptive_name(self):
11     """返回整洁的描述性信息"""
12     long_name = str(self.year) + ' ' + self.make + ' ' + self.model
13     return long_name.title()
14   def read_odometer(self):
15     """打印一条指出汽车里程的消息"""
16     print("This car has " + str(self.odometer_reading) + " miles on it.")
17   def update_odometer(self, mileage):
18     """将里程数读数设置为指定的值"""
19     self.odometer_reading = mileage
20 my_new_car = Car('audi', 'a4', 2016)
21 #print(my_new_car.get_descriptive_name())
22 my_new_car.update_odometer(23)
23 my_new_car.read_odometer()
通过方法修改属性的值
#!/usr/bin/env python
#-*- encoding:utf-8 -*-
class Car():
  """一次模拟汽车的简单尝试"""
  def __init__(self, make, model, year):
    self.make = make
    self.model = model
    self.year = year
    self.odometer_reading = 23
  def get_descriptive_name(self):
    """返回整洁的描述性信息"""
    long_name = str(self.year) + ' ' + self.make + ' ' + self.model
    return long_name.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)
my_new_car.update_odometer(10)
my_new_car.read_odometer()
添加逻辑
  • 通过方法对属性的值进行递增

 1 #!/usr/bin/env python
 2 #-*- encoding: utf-8 -*-
 3 class Car():
 4   """一次模拟汽车的简单尝试"""
 5   def __init__(self, make, model, year):
 6     """初始化描述汽车的属性"""
 7     self.make = make 
 8     self.model = model
 9     self.year = year
10     self.odometer_reading = 0
11   def get_descriptive_name(self):
12     """返回整洁的描述性信息"""
13     long_time = str(self.year) + ' ' + self.make + ' ' + self.model
14     return long_time.title()
15   def update_odometer(self, mileage):
16     """将里程表读数设置为指定值,禁止将里程表读数往回调"""
17     if mileage >= self.odometer_reading:
18       self.odometer_reading = mileage
19     else:
20       print("You can't roll back an odometer!")
21   def read_odometer(self):
22     """打印一条指出汽车里程的消息"""
23     print("This car has " + str(self.odometer_reading) + " miles on it. ")
24   def increment_odometer(self, miles):
25     """将里程表读数增加指定的量"""
26     self.odometer_reading += miles
27 my_used_car = Car('subaru', 'outback', 2013)
28 print(my_used_car.get_descriptive_name())
29 my_used_car.update_odometer(23500)
30 my_used_car.read_odometer()
31 my_used_car.increment_odometer(100)
32 my_used_car.read_odometer()
View Code
  • 2、继承

如果编写的类是另一个现成类的特殊版本,可使用继承。一个类集成另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。

  • 子类的方法__init__()

继承

Python2.7中的继承

1 #!/usr/bin/env python
2 #-*- encoding: utf-8 -*-
3 class Car():
4   def __init__(self, make, model, year):
5     --snip--
6 class ElectricCar(Car):
7   def ___init__(self, make, model, year):
8     super(ElectricCar, self).__init__(make, model, year)
9     --snip--
Python2.7类的继承
  • 子类定义属性和方法

 1 #!/usr/bin/env python
 2 #-*- encoding: utf-8 -*-
 3 #electric_car.py
 4 class Car():
 5   """一个模拟汽车的简单尝试"""
 6   def __init__(self, make, model, year):
 7     self.make = make
 8     self.model = model
 9     self.year = year
10     self.odometer_reading = 0
11   def get_descriptive_name(self):
12     long_time = str(self.year) + ' ' + self.make + ' ' + self.model
13     return long_time.title()
14   def read_odometer(self):
15     print("This car has " + str(self.odometer_reading) + " miles on it. ")
16   def update_odemeter(self, mileage):
17     if mileage >= self.odometer_reading:
18       self.odometer_reading = mileage
19     else:
20       print("You can't roll back an odometer!")
21   def increment_odometer(self, miles):
22     self.odometer_reading += miles
23 class ElectricCar(Car):
24   """电动汽车的独特之处,初始化父类的属性,再初始化电动汽车特有的属性"""
25   def __init__(self, make, model, year):
26     super().__init__(make, model, year)
27     self.bettery_size = 70
28   def describe_battery(self):
29     """打印一条描述电瓶容量的消息"""
30     print("This car has a " + str(self.bettery_size) + "-kWh battery.")
31 my_tesla = ElectricCar('tesla', 'model s', 2016)
32 print(my_tesla.get_descriptive_name())
33 my_tesla.describe_battery()
给子类定义属性和方法
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/demo2.py
2016 Tesla Model S
This car has a 70-kWh battery.

  子类添加了新属性self.battery_size(),并设置其初始值(70),根据ElectricCar类创建的所有实例都将包含这个属性,但所有Car实例都不包含它。

  • 重写父类的方法

 对于父类的方法,只要不符合子类模拟的事务的行为,都可对其进行重写。可在子类中定义一个这样的方法,即它与要重写的父类方法同名,这样,Python将不会考虑这个父类方法,而只关注在子类中定义的相应方法。

1 class ElectricCar(Car):
2   ---snip---
3   def fill_gas_tank():
4     """电动汽车没有油箱"""
5     print("This car doesn't need a gas tank!")
重写父类的方法
  • 将实例用作属性

 使用代码模拟事务时,会发现自己给类添加的细节越来越多:属性和方法清单以及文件越来越长。在这种情况下,可能需要将类的一部分作为一个独立的类提取出来。将大型类拆分成多个协同工作的小类。

  • 3、导入类

  • 导入单个类

 1 #!/usr/bin/env python
 2 #-*- encoding: utf-8 -*-
 3 class Car():
 4   """一个模拟汽车的简单尝试"""
 5   def __init__(self, make, model, year):
 6     self.make = make
 7     self.model = model
 8     self.year = year
 9     self.odometer_reading = 0
10   def get_descriptive_name(self):
11     long_time = str(self.year) + ' ' + self.make + ' ' + self.model
12     return long_time.title()
13   def read_odometer(self):
14     print("This car has " + str(self.odometer_reading) + " miles on it. ")
15   def update_odemeter(self, mileage):
16     if mileage >= self.odometer_reading:
17       self.odometer_reading = mileage
18     else:
19       print("You can't roll back an odometer!")
20   def increment_odometer(self, miles):
21     self.odometer_reading += miles
car.py
1 from car import Car
2 
3 my_new_car = Car('audi', 'a4', 2016)
4 print(my_new_car.get_descriptive_name())
5 my_new_car.odometer_reading = 23
6 my_new_car.read_odometer()
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/demo3.py
2016 Audi A4
This car has 23 miles on it.

posted on 2018-11-27 15:56  HelonTian  阅读(194)  评论(0编辑  收藏  举报