整体文章目录
一、 当前章节目录
二、面向对象的概述
-
用例图
是从客户的角度来描述系统功能。
-
活动图
本质上是流程图,描述系统的活动,判定点和分支。
-
状态图
通过建立对象的生存周期模型来描述对象随时间变化的动态行为。
-
类图
描述系统中类的静态结构。 -
序列图和协助图
表达对相见的交互过程及对象间的关联关系。
-
组件图和部署图
组件图:描述系统组件之间的交互,类和组件之间的依赖关系。
部署图:描述系统的部署及组件之间的配置。
三、类和对象
3.1 类和对象的区别
- 类:对客观世界中事物的抽象。
- 对象:类实例化后的实体。
3.2 类的定义
# 类的创建
class Fruit: # 定义Fruit类
def __init__(self): # __init__为类的构造函数,后面会详细介绍
self.name = name
self.color = color
def grow(self): # 定义grow函数,类中的函数称为方法
print("Fruit grow …")
3.3 对象的创建
# 类的创建
class Fruit: # 定义Fruit类
def grow(self): # 定义grow函数,类中的函数称为方法
print("Fruit grow …")
if __name__ == "__main__": # 判断本模块是否作为主程序运行
fruit = Fruit() # 实例化
fruit.grow() # 调用grow()方法
运行结果:
Fruit grow …
四、属性和方法
4.1 类的属性
class Fruit: # 定义Fruit类
price = 0 # 类属性
def __init__(self): # 定义init方法
self.color = "red" # 实例属性
zone = "China" # 局部变量
if __name__ == "__main__":
print(Fruit.price) # 使用类名调用类变量
apple = Fruit() # 实例化apple
print(apple.color) # 打印apple实例的颜色
Fruit.price = Fruit.price + 10 # 将类变量加10
print("apple's price:" + str(apple.price)) # 打印apple实例的price
banana = Fruit() # 实例化banana
print("banana's price:" + str(banana.price)) # 打印banana实例的price
运行结果:
0
red
apple’s price:10
banana’s price:10
# 访问私有属性
class Fruit:
def __init__(self):
self.__color = "red" # 私有变量使用双下划线开始的名称
if __name__ == "__main__":
apple = Fruit() # 实例化apple
print(apple._Fruit__color) # 调用类的私有变量
运行结果:
red
class Fruit:
def __init__(self):
self.__color = "red" # 定义私有变量
class Apple(Fruit): # Apple继承了Fruit
"""This is doc""" # doc文档
pass
if __name__ == "__main__":
fruit = Fruit()
apple = Apple()
print(Apple.__bases__) # 输出基类组成的元组
print(apple.__dict__) # 输出属性组成的字典
print(apple.__module__) # 输出类所在的模块名
print(apple.__doc__) # 输出doc文档
运行结果:
(<class ‘main.Fruit’>,)
{’_Fruit__color’: ‘red’}
main
This is doc
4.2 类的方法
class Fruit:
price = 0 # 类变量
def __init__(self):
self.__color = "red" # 定义私有变量
def getColor(self):
print(self.__color) # 打印私有变量
@ staticmethod # 使用@staticmethod修饰器静态方法
def getPrice():
print(Fruit.price)
def __getPrice(): # 定义私有函数
Fruit.price = Fruit.price + 10
print(Fruit.price)
count = staticmethod(__getPrice) # 使用staticmethod方法定义静态方法
@ staticmethod # 使用@staticmethod修饰器定义类方法
def getPrice2(cls):
print(cls.price)
def __getPrice2(cls):
cls.price = cls.price + 10
print(cls.price)
count2 = classmethod(__getPrice2) # 使用classmethod方法定义类方法
if __name__ == "__main__":
apple = Fruit() # 实例化apple
apple.getColor() # 使用实例调用静态方法
Fruit.count() # 使用类名调用静态方法
banana = Fruit()
Fruit.count()
Fruit.getPrice()
运行结果:
red
10
20
20
4.3 内部类的使用
class Car:
class Door: # 内部类
def open(self):
print("open door")
class Wheel: # 内部类
def run(self):
print("car run")
if __name__ == "__main__":
car = Car() # 实例化car
backDoor = car.Door() # 内部类的实例化方法一
frontDoor = Car.Door() # 内部类的实例化方法二
backDoor.open()
frontDoor.open()
wheel = Car.Wheel()
wheel.run()
运行结果:
open door
open door
car run
4.4 __init__方法
class Fruit:
def __init__(self, color): # 初始化属性__color
self.__color = color
print(self.__color)
def getColor(self):
print(self.__color)
def setColor(self, color):
self.__color = color
print(self.__color)
if __name__ == "__main__":
color = "red"
fruit = Fruit(color) # 带参数的构造函数
fruit.getColor()
fruit.setColor("blue")
运行结果:
red
red
blue
4.5 __del__方法
class Fruit:
def __init__(self, color): # 初始化属性__color
self.__color = color
print(self.__color)
def __del__(self):
self.__color = ""
print("free...")
def grow(self):
print("grow...")
if __name__ == "__main__":
color = "red"
fruit = Fruit(color) # 带参数的构造函数
fruit.grow()
del fruit
运行结果:
red
grow…
free…
4.6 垃圾回收机制
import gc
class Fruit:
def __init__(self, name, color): # 初始化name、color属性
self.__name = name
self.__color = color
def getColor(self):
return self.__color # 返回color
def setColor(self, color):
self.__color = color # 定义color
def getName(self):
return self.__name # 返回name
def setName(self, name):
self.__name = name # 定义name
class FruitShop: # 水果店类
def __init__(self):
self.fruits = []
def addFruit(self, fruit):
fruit.parent = self # 添加水果
self.fruits.append(fruit) # 把Fruit类关联到FruitShop类
if __name__ =="__main__":
shop = FruitShop()
shop.addFruit(Fruit("apple", "red"))
shop.addFruit(Fruit("banana", "yellow"))
print(gc.get_referrers(shop)) # 打印出shop关联的所有对象
del shop
print(gc.collect()) # 显式地调用垃圾回收器
运行结果:
[{’_Fruit__name’: ‘apple’, ‘_Fruit__color’: ‘red’, ‘parent’: <main.FruitShop object at 0x000002879474D1C0>}, {’_Fruit__name’: ‘banana’, ‘_Fruit__color’: ‘yellow’, ‘parent’: <main.FruitShop object at 0x000002879474D1C0>}, {‘name’: ‘main’, ‘doc’: None, ‘package’: None, ‘loader’: <_frozen_importlib_external.SourceFileLoader object at 0x00000287942208B0>, ‘spec’: None, ‘annotations’: {}, ‘builtins’: <module ‘builtins’ (built-in)>, ‘file’: ‘C:/Users/86155/Desktop/Python/第8章 面向对象编程/8.3 属性和方法/8.3.6 垃圾回收机制.py’, ‘cached’: None, ‘gc’: <module ‘gc’ (built-in)>, ‘Fruit’: <class ‘main.Fruit’>, ‘FruitShop’: <class ‘main.FruitShop’>, ‘shop’: <main.FruitShop object at 0x000002879474D1C0>}]
7
4.7 类的内置方法
- new()
class Singleton(object):
__instance = None # 定义实例
def __init__(self):
pass
def __new__(cls, *args, **kwd): # 在__init__之前调用
if Singleton.__instance is None: # 生成唯一实例
Singleton.__instance = object.__new__(cls, *args, **kwd)
return Singleton.__instance
- getattr(),setattr()和__getattribute__()
class Fruit(object):
def __init__(self, color = "red", price = 0):
self.__color = color
self.__price = price
def __getattribute__(self, name): # 获取属性的方法
return object.__getattribute__(self, name)
def __setattr__(self, name, value): # 设置属性的方法
self.__dict__[name] = value
if __name__ == "__main__":
fruit = Fruit("blue", 10)
print(fruit.__dict__.get("_Fruit__color")) # 获取color属性的值
fruit.__dict__["_Fruit__price"] = 5 # 使用__dict__进行赋值
print(fruit.__dict__.get("_Fruit__price")) # 获取price属性的值
运行结果:
blue
5
- getitem()
class FruitShop:
def __getitem__(self, i): # 获取水果店的水果
return self.fruits[i]
if __name__ == "__main__":
shop = FruitShop()
shop.fruits = ["apple", "banana"] # 给fruits赋值
print(shop[1])
for item in shop: # 输出水果店的水果
print(item, end="")
运行结果:
banana
applebanana
- str()
class Fruit:
'''Fruit类'''
def __str__(self): # 定义对象的字符串表示
return self.__doc__ # 返回heredoc
if __name__ == "__main__":
fruit = Fruit()
print(str(fruit)) # 调用__str__
print(fruit) # 与第8行代码结果相同
运行结果:
Fruit类
Fruit类
- call()
class Fruit:
class Growth: # 内部类
def __call__(self):
print("grow...")
grow = Growth() # 返回__call__的内容
if __name__ == '__main__':
fruit = Fruit()
fruit.grow() # 使用实例调用
Fruit.grow() # 使用类名调用
运行结果:
grow…
grow…
4.8 方法的动态特性
# 动态添加方法
class Fruit:
pass
def add(self): # 定义在类外的函数
print("grow...")
if __name__ == "__main__":
Fruit.grow = add # 动态添加add函数
fruit = Fruit()
fruit.grow()
运行结果:
grow…
# 动态更新方法
class Fruit():
def grow(self):
print("grow...")
def update():
print("grow... ...")
if __name__ == "__main__":
fruit = Fruit()
fruit.grow()
fruit.grow = update # 将grow方法更新为update()
fruit.grow()
运行结果:
grow…
grow… …
五、继承
5.1 使用继承
class Fruit: # 基类
def __init__(self, color):
self.color = color
print("fruit's color : %s" % self.color)
def grow(self):
print("grow...")
class Apple(Fruit): # 继承了Fruit类
def __init__(self, color): # 子类的构造函数
Fruit.__init__(self, color) # 显式调用父类的构造函数
print("apple's color : %s" % self.color)
class Banana(Fruit): # 继承Fruit类
def __init__(self, color): # 子类的构造函数
Fruit.__init__(self, color) # 显式调用父类的构造函数
print("banana's color : %s" % self.color)
def grow(self):
print("banana grow ...")
if __name__ == "__main__":
apple = Apple("red")
apple.grow() # 调用grow方法
banana = Banana("yellow")
banana.grow() # 调用grow方法
运行结果:
fruit’s color : red
apple’s color : red
grow…
fruit’s color : yellow
banana’s color : yellow
banana grow …
# 使用super()调用父类
class Fruit(object): # 定义基类,继承自object,python3.x中这不是必需的
def __init__(self):
print("parent")
class Apple(Fruit):
def __init__(self):
super(Apple, self).__init__() # 使用super()调用父类,更直观
print("child")
if __name__ == "__main__":
Apple()
运行结果:
parent
child
5.2 抽象基类
from abc import ABCMeta, abstractmethod # 引入所需的module
class Fruit(metaclass=ABCMeta): # 抽象类
@abstractmethod # 使用@abstractmethod修饰器定义抽象函数
def grow(self):
pass
class Apple(Fruit):
def grow(self): # 子类中必须重写抽象函数
print("Apple growing")
if __name__ == "__main__":
apple = Apple()
apple.grow()
# fruit = Fruit()
运行结果:
Apple growing
5.3 多态性
class Fruit: # 父类Fruit
def __init__(self, color = None):
self.color = color
class Apple(Fruit): # 继承Fruit的子类Apple
def __init__(self, color = "red"):
Fruit.__init__(self, color)
class Banana(Fruit): # 继承Fruit的子类Banana
def __init__(self, color = "yellow"):
Fruit.__init__(self, color)
class FruitShop:
def sellFruit(self, fruit):
if isinstance(fruit, Apple): # 判断参数fruit的类型
print("sell apple") # 根据类型做特殊的处理
if isinstance(fruit, Banana):
print("sell banana")
if isinstance(fruit, Fruit):
print("sell fruit")
if __name__ == "__main__":
shop = FruitShop()
apple = Apple("red")
banana = Banana("yellow")
shop.sellFruit(apple) # 参数的多态性,传递apple对象
shop.sellFruit(banana) # 参数的多态性,传递banana对象
运行结果:
sell apple
sell fruit
sell banana
sell fruit
5.4 多重继承
import gc
class Fruit:
def __init__(self):
print("initialize Fruit")
def grow(self): # 定义grow()方法
print("grow...")
class Vegetable(object):
def __init__(self):
print("initialize Vegetable")
def plant(self): # 定义plant方法
print("plant...")
class Watermelon(Vegetable, Fruit): # 多重继承,同时继承Vegetable和Fruit
pass
if __name__ == "__main__":
w = Watermelon() # 多重继承的子类,拥有父类的一切公有属性
w.grow()
w.plant()
运行结果:
initialize Vegetable
grow…
plant…
5.5 Mixin机制
class Fruit: # 父类
def __init__(self):
pass
class HuskedFruit(Fruit): # 削皮水果
def __init__(self):
print("initialize HuskedFruit")
def husk(self): # 削皮方法
print("husk...")
class DecorticatedFruit(Fruit): # 剥皮水果
def __init__(self):
print("initialize DecorticatedFruit")
def decorticat(self): # 剥皮方法
print("decorticat...")
class Apple(HuskedFruit):
pass
class Banana(DecorticatedFruit):
pass
class Fruit(object): # 水果
def __init__(self):
pass
class HuskedFruit(object): # 削皮水果
def __init__(self):
print("initialize HuskedFruit")
def husk(self): # 削皮方法
print("husk...")
class DecorticatedFruit(object): # 剥皮水果
def __init__(self):
print("initialize DecorticatedFruit")
def decorticat(self): # 剥皮方法
print("decorticat...")
class Apple(HuskedFruit, Fruit): # 是水果,并且是削皮水果
pass
class Banana(DecorticatedFruit, Fruit): # 是水果,并且是削皮水果
pass
六、运算符的重载
class Fruit:
def __init__(self, price = 0):
self.price = price
def __add__(self, other): # 重载加号运算符
return self.price + other.price
def __gt__(self, other): # 重载大于运算符
if self.price > other.price:
flag = True
else:
flag = False
return flag
class Apple(Fruit):
pass
class Banana(Fruit):
pass
if __name__ == "__main__":
apple = Apple(3)
print("苹果的价格:", apple.price)
banana = Banana(2)
print("香蕉的价格:", banana.price)
print(apple > banana) # >号为重载后的运算符
total = apple + banana # +号为重载后的运算符
print("合计:", total)
运行结果:
苹果的价格: 3
香蕉的价格: 2
True
合计: 5
import sys # 引入sys
class Stream:
def __init__(self, file):
self.file = file
def __lshift__(self, obj): # 对运算符<<进行重载
self.file.write(str(obj))
return self
class Fruit(Stream):
def __init__(self, price = 0, file = None):
Stream.__init__(self, file)
self.price = price
class Apple(Fruit):
pass
class Banana(Fruit):
pass
if __name__ == "__main__":
apple = Apple(2, sys.stdout) # apple对象可作为流输出
banana = Banana(3, sys.stdout)
endl = "\n"
apple<<apple.price<<endl # 使用重载后的<<运算符
banana<<banana.price<<endl
运行结果:
2
3
七、Python与设计模式
7.1 设计模式简介
- 设计模式是面向对象程序设计的解决方案,是复用性程序设计的经验总结。
7.2 设计模式示例——Python实现工厂方法
class Factory: # 工厂类
def createFruit(self, fruit): # 工厂方法
if fruit == "apple": # 如果是apple则返回类Apple
return Apple()
elif fruit == "banana": # 如果是banana则返回类Banana
return Banana()
class Fruit:
def __str__(self):
return "fruit"
class Apple(Fruit):
def __str__(self):
return "apple"
class Banana(Fruit):
def __str__(self):
return "banana"
if __name__ == "__main__":
factory = Factory()
print(factory.createFruit("apple")) # 创建apple对象
print(factory.createFruit("banana"))# 创建banana对象
运行结果:
apple
banana
八、习题
习题:
- 怎么查看一个类的所有属性?
- 为什么创建类函数的时候需要添加self变量?可以使用其他变量如this代替self?
- 怎么理解Python中一切皆对象?
- 汽车、轮船、火车等都属于交通工具。联系实际情况,编写类Traffic,并继承它实现类Car、Ship和Train。
答案:
print(dir(对象名))
self参数用于区分函数和类的方法。
self参数的名称可以是任意合法的变量名。建议使用self作为参数名,便于程序的阅读和程序的统一。而对于类方法,约定使用cls作为参数名。不论是int,str,还是dict,list,再或者是自己定义的类,实例化出来都是一个对象。
Python中函数、类、类型等等也都是对象。我们知道Python是动态类型语言,虽然不用声明类型,但是每个对象都隐藏着一个固定的类型(可以通过type(obj)查看),而这个类型也是一个对象。代码如下。
# 第4题
class Factory: # 工厂类
def createTraffic(self, traffic): # 工厂方法
if traffic == "car":
return Car()
elif traffic == "ship":
return Ship()
elif traffic == "train":
return Train()
class Traffic:
def __str__(self):
return "fruit"
class Car(Traffic):
def __str__(self):
return "car"
class Ship(Traffic):
def __str__(self):
return "ship"
class Train(Traffic):
def __str__(self):
return "train"
if __name__ == "__main__":
factory = Factory()
print(factory.createTraffic("car"))
print(factory.createTraffic("ship"))
print(factory.createTraffic("train"))
运行结果:
car
ship
train