一、类和对象基础
1. 类与对象的关系
- 类 (Class):具有相同特征和行为的对象的抽象模板
- 对象 (Object):根据类创建的具体实例
- 比喻:类相当于汽车设计图,对象相当于根据图纸生产的汽车
class Dog: # 定义类
pass
my_dog = Dog() # 创建对象
二、类的成员方法
1. 成员方法定义
- 定义在类中的函数
- 第一个参数必须是
self(指向对象实例的引用)
class Calculator:
def add(self, a, b): # 成员方法
return a + b
calc = Calculator()
print(calc.add(2, 3)) # 输出:5
2. 方法调用原理
- 实例调用方法时自动传递self参数
- 本质:
instance.method(args)等价于Class.method(instance, args)
三、构造方法 init
1. 特殊初始化方法
- 在对象创建时自动调用
- 用于初始化对象属性
class Person:
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
p = Person("Alice", 25)
print(p.name) # 输出:Alice
2. 构造方法特性
- 没有显式定义时,Python会自动创建空构造方法
- 可以有参数,用于接收初始化数据
- 不能有返回值(自动返回None)
四、魔术方法(特殊方法)
1. 特征说明
- 以双下划线开头和结尾的特殊方法
- 在特定场景自动触发
- 实现运算符重载和特殊行为
2. 常见魔术方法
(1) 对象表示
class Book:
def __init__(self, title):
self.title = title
def __str__(self): # 用户友好字符串
return f"Book: {self.title}"
def __repr__(self): # 开发者调试信息
return f"<Book '{self.title}'>"
b = Book("Python Guide")
print(str(b)) # Book: Python Guide
print(repr(b)) # <Book 'Python Guide'>
(2) 运算符重载
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # 实现加法
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other): # 判断相等
return self.x == other.x and self.y == other.y
v1 = Vector(2, 3)
v2 = Vector(1, 2)
v3 = v1 + v2
print(v3.x, v3.y) # 3 5
print(v1 == v2) # False
(3) 其他常用方法
class MyClass:
def __len__(self): # 定义len()行为
return 10
def __getitem__(self, key): # 支持索引访问
return key * 2
def __call__(self): # 使实例可调用
print("Instance called!")
obj = MyClass()
print(len(obj)) # 10
print(obj[3]) # 6
obj() # Instance called!
五、综合应用示例
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return f"存款成功,当前余额:{self.balance}"
def withdraw(self, amount):
if amount > self.balance:
return "余额不足"
self.balance -= amount
return f"取款成功,当前余额:{self.balance}"
def __str__(self):
return f"账户所有人:{self.owner}, 余额:{self.balance}"
def __add__(self, other):
return self.balance + other.balance
# 使用示例
acc1 = BankAccount("Alice", 1000)
acc2 = BankAccount("Bob", 500)
print(acc1) # 账户所有人:Alice, 余额:1000
print(acc1 + acc2) # 1500
print(acc1.deposit(200)) # 存款成功,当前余额:1200
六、总结
- 类定义对象模板,对象是类的具体实例
- 成员方法通过
self访问实例属性和方法 __init__方法用于初始化对象状态- 魔术方法实现特殊行为:
- 对象表示:
__str__,__repr__ - 运算符重载:
__add__,__eq__ - 其他特殊行为:
__len__,__call__
- 对象表示:
掌握这些核心概念,即可在Python中灵活运用面向对象编程范式,构建结构清晰、可维护的应用程序。