Python 类的运算

类的运算

运算的理解

Python 类的运算_第1张图片

算数运算符的重载

Python 类的运算_第2张图片
Python 类的运算_第3张图片
Python 类的运算_第4张图片
Python 类的运算_第5张图片
Python 类的运算_第6张图片

比较运算的重载

Python 类的运算_第7张图片

成员运算的重载

Python 类的运算_第8张图片
Python 类的运算_第9张图片
Python 类的运算_第10张图片

其他运算的重载

Python 类的运算_第11张图片
Python 类的运算_第12张图片Python 类的运算_第13张图片
Python 类的运算_第14张图片
Python 类的运算_第15张图片

小结

Python 类的运算_第16张图片

python 类的多态

多态的理解

Python 类的运算_第17张图片

参数类型的多态

Python 类的运算_第18张图片
技巧:用python内部支持多种参数类型的天然保留方法的重载,如__id__()

参数形式的多态

Python 类的运算_第19张图片
技巧:通过默认参数的形式去实现

小结

Python 类的运算_第20张图片

一个实例(图像之间的数据运算)

# 编写代码重载加减乘除四则运算,实现图像的加减乘除
# 原理是将图像每一个像素点的rgb三个值作对应的加减乘除运算
from PIL import Image
import numpy as np

class ImageObject:
	def __init__(self, path = ''):
		self.path = path
		try:
			self.data = np.array(Image.open(path)) #调用numpy库的array函数生成一个三维数组
		except:
			self.data = None
		
	def __add__(self, other):
		image = ImageObject()
		try:
			image.data = np.mod(self.data + other.data, 255) #numpy数据库取模函数
		except:
			image.data = self.data
		return image
	
	def __sub__(self, other):
		image = ImageObject()
		try:
			image.data = np.mod(self.data - other.data, 255) 
		except:
			image.data = self.data
		return image
		
	def __mul__(self, factor):
		image = ImageObject()
		try:
			image.data = np.mod(self.data * factor, 255) 
		except:
			image.data = self.data
		return image

	def __truediv__(self, factor):
		image = ImageObject()
		try:
			image.data = np.mod(self.data // factor, 255) 
		except:
			image.data = self.data
		return image

	def saveImage(self, path):
		try:
			im = Image.fromarray(self.data)
			im.save(path)
			return True
		except:
			return False

a = ImageObject("***")
b = ImageObject("***")
(a + b).saveImage("path****")
(a - b).saveImage("path****")
(a * b).saveImage("path****")
(a / b).saveImage("path****")	

以上所有内容来自嵩天老师《python面向对象精讲》,为学习截图与随堂笔记整理,方便日后复习使用

你可能感兴趣的:(python)