精通 Python 对象与类:实战指南
Python 对象与类
本教程探索 Python 核心面向对象特性,指导你完成类创建、实例化及编写健壮代码的最佳实践。
视频:Python 类与对象
Python 对象与类
Python 本质上是面向对象的。过程式编程关注函数,OOP 以对象为中心,将数据与行为捆绑。
对象是属性(数据)和方法(函数)的捆绑。类是定义对象结构的蓝图。
把类想象成房屋蓝图——详述房间、门、窗。每栋建成的房子是对象,即从蓝图创建的实例。
同一类可创建多个对象。实例化是从类创建对象的过程。
在 Python 中定义类
类定义以 class 关键字开始,类似函数以 def 开始。类中的第一个字符串是文档字符串,提供简短描述。
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
定义类会为其属性建立新命名空间,属性可以是数据或方法。以双下划线开头的特殊属性如 __doc__ 保存文档字符串等元数据。
定义后,创建类对象,可用于访问属性或实例化新对象。
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# 输出: 10
print(Person.age)
# 输出: <function Person.greet>
print(Person.greet)
# 输出: "This is a person class"
print(Person.__doc__)
输出
10 <function Person.greet at 0x7fc78c6e8160> This is a person class
在 Python 中创建对象
类作为对象工厂。实例化类似函数调用:
>>> harry = Person()
生成的对象 harry 可通过点号访问类属性。类方法成为实例上的绑定方法。
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# 创建 Person 类的新对象
harry = Person()
# 输出: <function Person.greet>
print(Person.greet)
# 输出: <bound method Person.greet of <__main__.Person object>>
print(harry.greet)
# 调用对象的 greet() 方法
# 输出: Hello
harry.greet()
输出
<function Person.greet at 0x7fd288e4e160> <bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>> Hello
注意方法定义中的 self 参数。方法在实例上调用时,Python 自动将实例作为第一个参数传递,使 harry.greet() 无需显式提供 self 即可执行。
惯例使用 self,虽语法上任何名称均可。遵循惯例增强可读性并符合社区标准。
Python 构造器
双下划线前缀的特殊方法扮演特殊角色。__init__ 方法在实例化时调用,充当构造器,初始化实例状态。
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
# 创建新 ComplexNumber 对象
num1 = ComplexNumber(2, 3)
# 调用 get_data() 方法
# 输出: 2+3j
num1.get_data()
# 创建另一 ComplexNumber 对象
# 并动态添加属性 'attr'
num2 = ComplexNumber(5)
num2.attr = 10
# 输出: (5, 0, 10)
print((num2.real, num2.imag, num2.attr))
# 访问缺失属性报错
print(num1.attr)
输出
2+3j (5, 0, 10) Traceback (most recent call last): File "<string>", line 27, in <module> print(num1.attr) AttributeError: 'ComplexNumber' object has no attribute 'attr'
此例演示属性可动态添加到单个实例而不影响其他实例。
删除属性和对象
用 del 语句移除属性。删除类方法或属性影响后续调用。
>>> num1 = ComplexNumber(2,3)
>>> del num1.imag
>>> num1.get_data()
Traceback (most recent call last): ... AttributeError: 'ComplexNumber' object has no attribute 'imag'
>>> del ComplexNumber.get_data
>>> num1.get_data()
Traceback (most recent call last): ... AttributeError: 'ComplexNumber' object has no attribute 'get_data'
对象本身也可删除。移除引用释放名称;若无其他引用,对象自动被垃圾回收。
>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last): ... NameError: name 'c1' is not defined
Python 通过引用计数和循环垃圾收集器管理内存,确保高效资源清理。

Python