py13,Python 类与对象基础——代码海洋的 “导航灯塔”
在探索 Python 类与对象基础的旅程中,我们可以类比数学中的一些概念。就像数学里的集合,类如同一个具有特定性质元素的集合定义,而对象则是集合中的具体元素。在代码海洋里,类与对象指引着编程方向,正如灯塔在茫茫大海中为船只导航,帮助我们梳理逻辑,构建有序的程序结构。
——开启学习之旅——
——类——
类的作用——抽象与建模
类是对现实世界或问题领域中事物的抽象。例如,在一个学校管理系统中,我们可以定义一个 “学生” 类。这个类能够抽象出学生共有的属性和行为。属性可能包括姓名、年龄、学号、班级等,行为可能有学习课程、参加考试等。通过定义 “学生” 类,我们把对学生的各种复杂的细节进行了提炼,形成一个统一的模板。
从数学角度看,类就像是一个数学模型。比如在几何中,“三角形” 类可以抽象出三角形的共同特征,如三条边的长度属性和计算面积、周长等行为。这使得我们在研究三角形相关问题时,有一个统一的模型可以依据,不用每次都重新考虑三角形的基本定义。
- 例1、任意三角形的周长和面积。
import math
class x:
def __init__(self, side_a, side_b, side_c):
self.side_a = side_a
self.side_b = side_b
self.side_c = side_c
#定义周长函数
def t(self):
return self.side_a + self.side_b + self.side_c
#用海伦公司求面积
def y(self):
s = self.t() / 2
return math.sqrt(s * (s - self.side_a) * (s - self.side_b) * (s - self.side_c))
a=int(input('请输入边长a='))
b=int(input('请输入边长b='))
c=int(input('请输入边长c='))
# 创建一个具体的三角形对象实例
x = x(a, b, c)
print("三角形的周长:", x.t())
print("三角形的面积:", x.y())
在上述代码中,x 类抽象出了三角形的通用特征,即三条边的长度以及相关的计算行为(周长和面积计算)。
__init__方法有四个参数。第一个参数self代表类的实例本身(这是 Python 的一个约定,必须是第一个参数),side_a, side_b, side_c是我们要传入的参数。在方法内部,我们通过self.side_a = side_a这个对象的实例设置了属性。
类的作用——代码组织与复用
类可以把相关的数据(属性)和操作(方法)整合在一起,让代码结构清晰明了,并且类具有很强的复用性,在不同的场景中只要涉及到同类事物的处理,都可以重复使用已定义好的类。
- 例2、以计算不同几何图形的面积为例,我们先定义一个基类 Shape 用于统一表示几何形状,然后派生出具体的几何图形类(如 Rectangle(矩形)、Circle(圆)等),它们都复用了 Shape 类中一些通用的概念,并各自实现计算面积的方法。
import math
class Shape:
def __init__(self, name):
self.name = name
class Rectangle(Shape):
def __init__(self, length, width, name="矩形"):
super().__init__(name)
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius, name="圆"):
super().__init__(name)
self.radius = radius
def calculate_area(self):
return math.pi * self.radius ** 2
a=int(input('长方形的长a='))
b=int(input('长方形的宽b='))
r=int(input('圆的半径r='))
# 创建矩形对象并计算其面积
rectangle = Rectangle(a, b)
print(rectangle.name, "的面积:", rectangle.calculate_area())
# 创建圆对象并计算其面积
circle = Circle(r)
print(circle.name, "的面积:", circle.calculate_area())
在这个例子中,Shape 类作为一个基础的抽象类对几何形状进行了基本的组织,定义了通用的 name 属性。然后 Rectangle 类和 Circle 类继承自 Shape 类,并分别实现了适合自身的 calculate_area 方法来计算面积。这种方式使得代码结构清晰,并且在不同几何图形面积计算场景中复用了相关的类结构,类似数学中一些通用的计算原理(如面积计算的基础概念)在不同图形计算中可以复用。
super是一个内置函数,主要用于在子类中调用父类的方法。它提供了一种方便的方式来访问父类的属性和方法,这在类的继承体系中非常有用。
类的作用——封装与数据隐藏
类通过封装机制可以隐藏对象内部的实现细节,对外只暴露必要的接口,这样能保证数据的安全性和一致性,外部代码只能通过规定的方法来访问和操作对象的数据,避免了直接对数据的随意篡改。
- 例3、假设我们要模拟一个简单的数学计算器类 Calculator,它内部有一些运算的中间数据和结果,但是不希望外部直接访问这些内部数据,只通过特定的方法来进行运算操作。
class Calculator:
def __init__(self):
self.__result = 8 # 使用双下划线开头表示私有属性,外部不能直接访问
def add(self, num):
self.__result += num
return self.__result
def subtract(self, num):
self.__result -= num
return self.__result
def get_result(self):
return self.__result
a=int(input('加数a='))
b=int(input('减数b='))
# 创建计算器对象并进行操作
calc = Calculator()
print("初始结果:", calc.get_result())
print(f"加 {a} 后的结果:", calc.add(a))
print(f"再减 {b} 后的结果:", calc.subtract(b))
在 Calculator 类中,__result 是私有属性,外部代码不能直接获取或修改它,只能通过 add、subtract 和 get_result 这些公开的方法来操作和获取运算结果,这就如同在数学计算中,我们通过计算器上规定的按键(方法)来得到结果,而不需要了解计算器内部是如何存储和处理数据的,保证了数据处理的规范性和安全性。
——对象——
对象的作用——具体实例化
对象是类的具体实例,它代表了类所描述的事物中的一个具体个体,每个对象都有类定义的属性和方法,并且属性具有特定的值,体现了类的具体表现形式。
- 例4、以三角形为例,我们前面定义了 Triangle 类,现在可以创建多个不同的三角形对象,每个对象都有其特定的边长值,对应着不同的具体三角形。
import math
class x:
def __init__(self, side_a, side_b, side_c):
self.side_a = side_a
self.side_b = side_b
self.side_c = side_c
def y(self):
return self.side_a + self.side_b + self.side_c
def s(self):
s = self.y() / 2
return math.sqrt(s * (s - self.side_a) * (s - self.side_b) * (s - self.side_c))
# 创建两个不同的三角形对象实例
x1 = x(3, 4, 5)
x2 = x(5, 12, 13)
print("第一个三角形的周长:", x1.y())
print("第一个三角形的面积:", x1.s())
print("第二个三角形的周长:", x2.y())
print("第二个三角形的面积:", x2.s())
这里 x1 和 x2 就是 x 类的两个具体对象实例,它们各自有不同的边长属性值,通过调用类中定义的方法,可以分别计算出各自的周长和面积,就像在数学中研究不同具体三角形的具体属性一样。
对象的作用——状态保持与交互
对象能够保存自身的状态(属性值),并且不同对象之间可以相互交互,根据彼此的状态改变来进行相应的操作,从而实现复杂的功能或模拟现实场景中的各种关系。
- 例题5、考虑一个简单的几何图形组合场景,有一个矩形和一个圆,我们希望判断它们是否相交,并计算相交部分的面积。
import math
# 矩形类
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def is_intersect_with(self, other_shape):
if isinstance(other_shape, Circle):
# 简单判断逻辑,实际可能更复杂
circle_center_x = other_shape.x
circle_center_y = other_shape.y
circle_radius = other_shape.radius
rect_min_x = self.x
rect_min_y = self.y
rect_max_x = self.x + self.width
rect_max_y = self.y + self.height
if (circle_center_x >= rect_min_x and circle_center_x <= rect_max_x and
circle_center_y >= rect_min_y and circle_center_y <= rect_max_y):
return True
return False
def calculate_intersect_area(self, circle):
"""
计算矩形和圆相交部分的面积,使用了一些简化的几何计算逻辑
"""
# 先判断是否相交,如果不相交返回0
if not self.is_intersect_with(circle):
return 0
# 计算相交情况,这里分几种情况来考虑
intersection_area = 0
circle_center_x = circle.x
circle_center_y = circle.y
circle_radius = circle.radius
# 计算矩形四个顶点到圆心的距离
distances = [
math.sqrt((self.x - circle_center_x) ** 2 + (self.y - circle_center_y) ** 2),
math.sqrt((self.x + self.width - circle_center_x) ** 2 + (self.y - circle_center_y) ** 2),
math.sqrt((self.x - circle_center_x) ** 2 + (self.y + self.height - circle_center_y) ** 2),
math.sqrt((self.x + self.width - circle_center_x) ** 2 + (self.y + self.height - circle_center_y) ** 2)
]
# 情况一:圆完全在矩形内部
if all(d <= circle_radius for d in distances):
intersection_area = math.pi * circle_radius ** 2
# 情况二:矩形的四个顶点都在圆外,需要用扇形面积和三角形面积来计算
elif all(d > circle_radius for d in distances):
# 分别计算四个角上的扇形面积和三角形面积,再求和得到相交面积
for i in range(4):
start_angle = 0
end_angle = 0
# 根据顶点位置计算起始角度和结束角度(这里简化示意,实际更复杂)
if i == 0:
start_angle = math.atan2(self.y - circle_center_y, self.x - circle_center_x)
end_angle = math.atan2(self.y + self.height - circle_center_y, self.x - circle_center_x)
elif i == 1:
start_angle = math.atan2(self.y + self.height - circle_center_y, self.x + self.width - circle_center_x)
end_angle = math.atan2(self.y - circle_center_y, self.x + self.width - circle_center_x)
elif i == 2:
start_angle = math.atan2(self.y - circle_center_y, self.x - circle_center_x)
end_angle = math.atan2(self.y + self.height - circle_center_y, self.x - circle_center_x)
elif i == 3:
start_angle = math.atan2(self.y + self.height - circle_center_y, self.x + self.width - circle_center_x)
end_angle = math.atan2(self.y - circle_center_y, self.x + self.width - circle_center_x)
sector_angle = end_angle - start_angle
if sector_angle < 0:
sector_angle += 2 * math.pi
sector_area = (sector_angle / (2 * math.pi)) * math.pi * circle_radius ** 2
triangle_area = 0.5 * circle_radius ** 2 * math.sin(sector_angle)
intersection_area += sector_area - triangle_area
# 情况三:其他更复杂的相交情况,暂不详细处理,可进一步完善代码来精确计算
else:
intersection_area = -1 # 表示还未精确处理的复杂情况
return intersection_area
# 圆类
class Circle:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
# 创建矩形对象和圆对象
rectangle = Rectangle(0, 0, 5, 5)
circle = Circle(3, 3, 2)
# 判断是否相交并输出相应信息
if rectangle.is_intersect_with(circle):
print("矩形和圆相交")
intersect_area = rectangle.calculate_intersect_area(circle)
print("相交部分的面积:", intersect_area)
else:
print("矩形和圆不相交")
在calculate_intersect_area方法里,先是用is_intersect_with方法判断图形是否相交,不相交就返回 0。若相交,会计算矩形四个顶点到圆心距离存进distances列表,用于后续判断。
处理 “情况二” 时,要算四个角上的扇形和三角形面积。算扇形面积,先通过atan2函数确定圆心角并处理角度范围,再按比例算出;三角形面积用公式结合三角函数来算。最后把每个角上扇形面积减去三角形面积的结果累加,就是相交面积。不过复杂相交情况处理较简化,可进一步优化完善。
——作者小语——
类仿若对某一事或物的详尽蓝图与精准刻画,它勾勒出事物的轮廓、属性与行为模式,是抽象概念的具化呈现。而对象则似依照这一蓝图精心打造的实体成果,是类在现实世界或特定情境中的实例化映射,二者相辅相成,共同构建起编程世界中井然有序且富有逻辑的架构体系。