Python 类基础
什么是面向对象编程?
面向对象编程(Object-Oriented Programming, OOP)是一种编程范式,它使用"对象"这一概念来组织和构建代码。在Python中,一切皆为对象 - 整数、字符串、函数,甚至是模块。面向对象编程的核心是类和对象。
- 类(Class) 是一个蓝图或模板,定义了对象的属性和行为。
- 对象(Object) 是类的实例,代表了现实世界中的实体。
提示
面向对象编程的四大特性:封装、继承、多态和抽象。在这篇教程中,我们将重点关注类的基础概念。
定义一个类
在Python中,我们使用class
关键字来定义一个类:
python
class Dog:
# 类变量
species = "Canis familiaris"
# 初始化方法
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
# 实例方法
def bark(self):
return "Woof!"
def get_description(self):
return f"{self.name} is {self.age} years old"
让我们分析这个类的组成部分:
- 类定义:使用
class
关键字后跟类名和冒号。 - 类变量:
species
是一个类变量,它在所有该类的实例之间共享。 - 初始化方法:
__init__
是一个特殊方法,当创建类的新实例时自动调用。 - 实例变量:
self.name
和self.age
是实例变量,每个实例都有自己的副本。 - 实例方法:
bark()
和get_description()
是实例方法,可以访问和修改实例的状态。
创建类的实例
一旦定义了类,我们就可以创建该类的实例(对象):
python
# 创建Dog类的两个实例
buddy = Dog("Buddy", 5)
miles = Dog("Miles", 3)
# 访问实例变量
print(buddy.name) # 输出: Buddy
print(miles.age) # 输出: 3
# 调用实例方法
print(buddy.bark()) # 输出: Woof!
print(miles.get_description()) # 输出: Miles is 3 years old
# 访问类变量
print(buddy.species) # 输出: Canis familiaris
print(miles.species) # 输出: Canis familiaris
理解self参数
在类的方法中,self
是一个特殊参数,它指向调用该方法的实例。通过self
,我们可以访问实例的属性和其他方法。
备注
self
不是Python的关键字,你可以使用其他名称,但按照惯例,我们通常使用self
。
python
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius * self.radius
def calculate_circumference(self):
return 2 * 3.14 * self.radius
# 创建Circle类的实例
my_circle = Circle(5)
print(f"Area: {my_circle.calculate_area()}") # 输出: Area: 78.5
print(f"Circumference: {my_circle.calculate_circumference()}") # 输出: Circumference: 31.4
类变量vs实例变量
- 类变量:属于类本身,在所有实例之间共享。
- 实例变量:属于类的特定实例,每个实例都有自己的副本。
python
class Student:
# 类变量
school = "Python Academy"
def __init__(self, name, grade):
# 实例变量
self.name = name
self.grade = grade
# 创建Student类的实例
alice = Student("Alice", 85)
bob = Student("Bob", 92)
print(alice.school) # 输出: Python Academy
print(bob.school) # 输出: Python Academy
# 修改类变量
Student.school = "Code University"
print(alice.school) # 输出: Code University
print(bob.school) # 输出: Code University
# 修改实例变量
alice.grade = 90
print(alice.grade) # 输出: 90
print(bob.grade) # 输出: 92 (bob的grade没有改变)
特殊方法(魔术方法)
Python类有许多特殊方法,它们以双下划线开头和结尾,例如__init__
。这些方法允许类与Python的内置函数和操作符交互。
python
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
# 定义对象的字符串表示
def __str__(self):
return f"{self.title} by {self.author}"
# 定义对象的官方表示
def __repr__(self):
return f"Book('{self.title}', '{self.author}', {self.pages})"
# 定义长度操作行为
def __len__(self):
return self.pages
# 创建Book类的实例
my_book = Book("Python Basics", "John Doe", 200)
print(my_book) # 输出: Python Basics by John Doe
print(repr(my_book)) # 输出: Book('Python Basics', 'John Doe', 200)
print(len(my_book)) # 输出: 200
实际应用案例:银行账户系统
让我们创建一个简单的银行账户系统来展示类的实际应用:
python
class BankAccount:
# 类变量
interest_rate = 0.03
def __init__(self, account_number, holder_name, balance=0):
self.account_number = account_number
self.holder_name = holder_name
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
return f"Deposited ${amount}. New balance: ${self.balance}"
else:
return "Deposit amount must be positive"
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
return f"Withdrew ${amount}. New balance: ${self.balance}"
else:
return "Invalid withdrawal amount or insufficient funds"
def apply_interest(self):
interest = self.balance * BankAccount.interest_rate
self.balance += interest
return f"Applied interest: ${interest:.2f}. New balance: ${self.balance:.2f}"
def get_balance(self):
return f"Current balance: ${self.balance}"
# 创建账户并执行操作
account1 = BankAccount("12345", "John Smith", 1000)
account2 = BankAccount("67890", "Jane Doe")
print(account1.get_balance()) # 输出: Current balance: $1000
print(account2.get_balance()) # 输出: Current balance: $0
print(account1.deposit(500)) # 输出: Deposited $500. New balance: $1500
print(account2.deposit(300)) # 输出: Deposited $300. New balance: $300
print(account1.withdraw(200)) # 输出: Withdrew $200. New balance: $1300
print(account2.withdraw(400)) # 输出: Invalid withdrawal amount or insufficient funds
print(account1.apply_interest()) # 输出: Applied interest: $39.00. New balance: $1339.00
在这个例子中:
BankAccount
类模拟了银行账户的基本功能- 类变量
interest_rate
表示所有账户共享的利率 - 实例方法如
deposit()
、withdraw()
和apply_interest()
实现了账户的基本操作 - 每个账户都是一个独立的实例,拥有自己的账号、持有人姓名和余额
总结
在本教程中,我们学习了:
- 如何定义Python类和创建实例
- 类变量和实例变量的区别
- 实例方法的创建和使用
self
参数的作用- 特殊方法(魔术方法)的基本用法
- 通过银行账户系统的实例,展示了类在实际应用中的用处
类是Python面向对象编程的基础,掌握它们将帮助你组织代码并解决复杂问题。在后续教程中,我们将探索更高级的概念,如继承、多态和封装。
练习
为了巩固所学知识,尝试完成以下练习:
- 创建一个
Rectangle
类,包含计算面积和周长的方法。 - 扩展
Student
类,添加计算平均成绩的方法。 - 创建一个
Product
类来模拟在线商店中的产品,包括名称、价格和库存等属性,以及购买和补货等方法。
提示
记住,面向对象编程是一种思维方式,需要通过实践来掌握。尝试识别现实问题中的对象,并将其建模为类!