我会从最基础的开始,逐步深入,让你完全理解这个过程。

核心概念:类 vs. 实例
- 类:像一个蓝图或模板,它定义了一类事物应该具有的属性(特征)和方法(行为)。
- 实例:根据这个蓝图创建出来的具体对象,每个实例都是独立的,拥有自己的属性值。
创建你的第一个类和对象
这是一个非常简单的例子,创建一个 Dog 类,然后创建几只狗的实例。
步骤 1: 定义类
使用 class 关键字来定义一个类,按照 Python 的命名约定,类名通常使用 驼峰命名法(CamelCase)。
# 定义一个 Dog 类
class Dog:
# 这是一个特殊方法,称为构造函数或初始化方法
# 当创建一个新的 Dog 实例时,这个方法会自动被调用
def __init__(self, name, age, breed):
# self.name 是一个实例属性
# 它将传入的 name 参数赋值给当前实例的 name 属性
self.name = name
self.age = age
self.breed = breed
# 也可以在内部定义属性,不依赖外部传入
self.is_awake = True
# 这是一个实例方法,定义了 Dog 对象的行为
def bark(self):
print(f"{self.name} says: Woof! Woof!")
def celebrate_birthday(self):
self.age += 1
print(f"Happy birthday to {self.name}! They are now {self.age} years old.")
def sleep(self):
self.is_awake = False
print(f"{self.name} is now sleeping.")
def wake_up(self):
self.is_awake = True
print(f"{self.name} has woken up.")
代码解释
class Dog:: 声明我们正在创建一个名为Dog的类。def __init__(self, name, age, breed):: 这是构造函数。__init__是一个特殊方法,用于初始化新创建的对象。self: 这是最重要的部分!self代表实例本身,当你调用一个实例的方法或访问其属性时,Python 会自动把这个实例作为第一个参数传递给方法,在方法内部,你必须使用self来引用实例的属性(如self.name)和其他方法(如self.bark())。name,age,breed: 这些是创建实例时需要提供的参数。
self.name = name: 这行代码的意思是:“将传入的name值,存储在当前实例的name属性中”,这样,每个Dog实例都会有自己独立的name。
步骤 2: 创建实例(对象)
现在我们可以使用 Dog 这个蓝图来创建具体的狗对象了。
# 创建第一个 Dog 实例
dog1 = Dog("Buddy", 3, "Golden Retriever")
# 创建第二个 Dog 实例
dog2 = Dog("Lucy", 5, "German Shepherd")
# 创建第三个 Dog 实例
dog3 = Dog("Max", 1, "Pug")
dog1, dog2, dog3 就是三个独立的 Dog 对象。

步骤 3: 使用实例
我们可以访问实例的属性和调用它们的方法。
# --- 访问实例属性 ---
print(f"{dog1.name} is a {dog1.breed}.")
# 输出: Buddy is a Golden Retriever.
print(f"{dog2.name} is {dog2.age} years old.")
# 输出: Lucy is 5 years old.
# --- 调用实例方法 ---
dog1.bark()
# 输出: Buddy says: Woof! Woof!
dog2.celebrate_birthday()
# 输出: Happy birthday to Lucy! They are now 6 years old.
# --- 展示实例的独立性 ---
print(f"Before sleeping, {dog3.name} is awake: {dog3.is_awake}")
# 输出: Before sleeping, Max is awake: True
dog3.sleep()
print(f"After sleeping, {dog3.name} is awake: {dog3.is_awake}")
# 输出: Max is now sleeping.
# 输出: After sleeping, Max is awake: False
# dog1 的状态不受影响
print(f"{dog1.name}'s awake status is still: {dog1.is_awake}")
# 输出: Buddy's awake status is still: True
一个更完整的例子:BankAccount 类
让我们再看一个更贴近实际的例子,一个银行账户类。
class BankAccount:
# 类变量:所有实例共享这个变量
bank_name = "Python National Bank"
def __init__(self, owner_name, balance=0):
# 实例变量:每个实例独有
self.owner_name = owner_name
self.balance = balance
def deposit(self, amount):
"""存款"""
if amount > 0:
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
"""取款"""
if amount > 0:
if self.balance >= amount:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
else:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
def get_balance(self):
"""查询余额"""
print(f"{self.owner_name}'s balance is: ${self.balance}")
return self.balance
def __str__(self):
"""返回对象的字符串表示,方便打印"""
return f"Account Owner: {self.owner_name}, Balance: ${self.balance}, Bank: {self.bank_name}"
# --- 创建和使用 BankAccount 实例 ---
account1 = BankAccount("Alice", 100)
account2 = BankAccount("Bob")
# 打印账户信息 (会自动调用 __str__ 方法)
print(account1)
# 输出: Account Owner: Alice, Balance: $100, Bank: Python National Bank
print(account2)
# 输出: Account Owner: Bob, Balance: $0, Bank: Python National Bank
# 操作账户
account1.get_balance()
# 输出: Alice's balance is: $100
account1.deposit(50)
# 输出: Deposited $50. New balance: $150
account1.withdraw(75)
# 输出: Withdrew $75. New balance: $75
account2.deposit(200)
# 输出: Deposited $200. New balance: $200
# 尝试透支
account2.withdraw(250)
# 输出: Insufficient funds.
总结关键点
- 定义类: 使用
class ClassName:。 - 构造函数:
__init__(self, ...)用于初始化实例。self是必须的,代表实例本身。 - 实例属性: 在
__init__中使用self.attribute = value来创建,每个实例都有自己独立的副本。 - 实例方法: 定义在类中的函数,第一个参数必须是
self,用来操作实例的属性。 - 创建实例:
instance_name = ClassName(...)。 - 访问属性:
instance.attribute。 - 调用方法:
instance.method()。
通过这种方式,你可以创建结构清晰、可复用、易于维护的代码,这是 Python 面向对象编程的强大之处。
