类与对象
面向对象编程把数据和操作数据的函数组织在一起。类是模板,对象是按模板创建的实例。
class Dog:
species = "犬科" # 类属性,所有实例共享
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
def bark(self):
return f"{self.name}:汪汪!"
d = Dog("旺财", 3)
print(d.bark()) # 旺财:汪汪!
print(d.species) # 犬科
__init__是构造方法,创建对象时自动调用;self指向当前对象,实例方法的第一个参数必须是它。
特殊方法
以双下划线开头和结尾的方法可以定制对象的行为:
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4)) # Vector(4, 6)
dataclass
只用来保存数据的类,用 dataclasses 可以省去大量样板代码:
from dataclasses import dataclass
@dataclass
class Book:
title: str
price: float = 0.0
b = Book("Python 入门", 59.0)
print(b) # Book(title='Python 入门', price=59.0)练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 定义 BankAccount 类,支持存款、取款(余额不足时抛出异常)和查询余额。
查看参考答案
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("余额不足")
self.balance -= amount
acc = BankAccount("小明", 100)
acc.deposit(50)
acc.withdraw(30)
print(acc.owner, acc.balance)
try:
acc.withdraw(500)
except ValueError as e:
print(e)参考输出:
小明 120
余额不足练习 2 为 Point 类实现 __eq__ 和 __repr__,使两个坐标相同的点比较结果为 True。
查看参考答案
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __repr__(self):
return f"Point({self.x}, {self.y})"
print(Point(1, 2) == Point(1, 2), Point(1, 2))参考输出:
True Point(1, 2)