一、self 与 cls 是什么
在 Python 中,self 和 cls 都不是关键字,而是约定俗成的参数名称。
它们分别表示不同层次的对象:
| 参数 | 表示对象 | 常见使用位置 | 主要用途 |
|---|---|---|---|
self |
当前实例对象 | 实例方法 | 访问实例属性和实例方法 |
cls |
当前类对象 | 类方法 | 访问类属性和类方法 |
简单理解:
self代表某个具体创建出来的对象。cls代表对象所属的类或当前调用的类。
例如:
class Person:
species = "Human"
def __init__(self, name):
self.name = name
def introduce(self):
print(f"My name is {self.name}")
@classmethod
def show_species(cls):
print(cls.species)
person = Person("Alice")
person.introduce()
Person.show_species()
输出:
My name is Alice
Human
这里:
self.name访问当前实例的name属性。cls.species访问当前类的species属性。
二、self 的含义与作用
self 是实例方法中的第一个参数,用于接收调用该方法的实例对象。
当通过实例调用实例方法时,Python 会自动将实例对象绑定为方法的第一个参数。
1. self 表示当前实例
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"姓名:{self.name}")
print(f"年龄:{self.age}")
student = Student("Alice", 20)
student.introduce()
输出:
姓名:Alice
年龄:20
在 introduce() 方法中,self 指向当前的 student 实例。
因此:
self.name
实际上就是访问当前实例的 name 属性。
2. self 不是 Python 关键字
Python 并没有规定实例方法的第一个参数必须叫 self。
下面的代码在语法上也是合法的:
class Student:
def __init__(this, name):
this.name = name
def introduce(this):
print(this.name)
student = Student("Alice")
student.introduce()
输出:
Alice
但是,这种写法不符合 Python 社区的通用约定。
推荐始终使用 self,因为它能够让其他开发者快速识别当前实例。
3. self 用于访问实例属性
实例属性通常通过 self.attribute 的形式定义和访问。
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def show_balance(self):
print(self.balance)
account = Account("Alice", 1000)
account.deposit(500)
account.show_balance()
输出:
1500
这里:
self.owner保存账户所有者。self.balance保存当前账户余额。self.balance += amount修改当前实例的余额。
4. 不同实例拥有不同的 self
class User:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}")
user1 = User("Alice")
user2 = User("Bob")
user1.greet()
user2.greet()
输出:
Hello, Alice
Hello, Bob
虽然两个实例调用的是同一个方法,但方法执行时接收到的 self 不同。
因此,同一个实例方法可以操作不同实例各自的数据。
三、self 的自动绑定机制
理解 self,最重要的是理解 Python 的方法绑定机制。
1. 通过实例调用方法
class Person:
def introduce(self):
print("Hello")
person = Person()
person.introduce()
调用:
person.introduce()
Python 会自动将 person 作为第一个参数传入。
从概念上可以理解为:
Person.introduce(person)
两种调用方式在这个示例中具有相同的核心效果。
2. 通过类调用实例方法
也可以直接通过类调用实例方法:
class Person:
def introduce(self):
print("Hello")
person = Person()
Person.introduce(person)
输出:
Hello
此时必须显式传入实例对象,因为通过类访问普通函数时,不会自动绑定某个具体实例。
如果省略参数:
Person.introduce()
就会产生 TypeError,因为缺少必需的 self 参数。
3. 实例方法绑定过程
flowchart TD
A["定义实例方法"] --> B["通过实例访问方法"]
B --> C["获取函数描述符"]
C --> D["创建绑定方法"]
D --> E["绑定当前实例 self"]
E --> F["调用方法"]
F --> G["执行方法体"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Python 中,普通函数作为类属性时具有描述符行为。
当通过实例访问普通函数时,函数的描述符机制会生成绑定方法,将实例作为第一个参数。
可以通过以下代码观察:
class Person:
def introduce(self):
print("Hello")
person = Person()
print(Person.introduce)
print(person.introduce)
输出形式类似:
<function Person.introduce at ...>
<bound method Person.introduce of <__main__.Person object at ...>>
区别在于:
Person.introduce是类上的函数对象。person.introduce是绑定到具体实例的方法对象。
4. 使用 self 和 func 观察绑定方法
绑定方法对象提供了两个重要属性:
__self__:方法绑定的实例。__func__:原始函数对象。
class Person:
def introduce(self):
print("Hello")
person = Person()
method = person.introduce
print(method.__self__ is person)
print(method.__func__ is Person.introduce)
输出:
True
True
这说明绑定方法并不是简单地复制了一份函数,而是将函数与实例关联起来。
四、cls 的含义与作用
cls 通常用于类方法的第一个参数,表示当前类对象。
类方法通过 @classmethod 装饰器定义。
class Person:
species = "Human"
@classmethod
def show_species(cls):
print(cls.species)
Person.show_species()
输出:
Human
这里的 cls 指向 Person 类。
1. cls 表示当前类
class Animal:
category = "动物"
@classmethod
def show_category(cls):
print(cls.__name__)
print(cls.category)
Animal.show_category()
输出:
Animal
动物
其中:
cls.__name__
表示当前类的名称。
而:
cls.category
访问当前类的属性。
2. cls 不是 Python 关键字
与 self 一样,cls 也是约定俗成的名称。
class Person:
@classmethod
def show(this_class):
print(this_class.__name__)
Person.show()
输出:
Person
虽然代码可以执行,但建议统一使用 cls。
3. cls 常用于访问类属性
class Configuration:
environment = "development"
debug = True
@classmethod
def show_config(cls):
print(cls.environment)
print(cls.debug)
Configuration.show_config()
输出:
development
True
类方法通过 cls 访问类级别的数据。
需要注意,类属性也可以通过实例访问,但类方法更适合表达与类本身相关的操作。
五、cls 的自动绑定机制
类方法与实例方法类似,也具有自动绑定机制。
区别在于:
- 实例方法自动绑定实例对象。
- 类方法自动绑定类对象。
1. 通过类调用类方法
class Person:
@classmethod
def show(cls):
print(cls)
Person.show()
输出:
<class '__main__.Person'>
调用时,Python 自动将 Person 作为第一个参数传入。
从概念上可以理解为:
Person.show()
等价于:
Person.__dict__["show"].__get__(None, Person)()
这里展示的是描述符绑定机制的表达形式。
对于 classmethod,也可以简单理解为:
Person.show(Person)
但实际访问过程还包含描述符绑定行为。
2. 通过实例调用类方法
class Person:
@classmethod
def show(cls):
print(cls.__name__)
person = Person()
person.show()
输出:
Person
虽然通过实例调用,但类方法接收到的仍然是类对象,而不是实例对象。
因此,类方法不依赖某个具体实例。
3. 类方法绑定过程
flowchart TD
A["定义类方法"] --> B["应用 classmethod 装饰器"]
B --> C["通过类或实例访问"]
C --> D["执行类方法描述符"]
D --> E["绑定当前类 cls"]
E --> F["调用方法"]
F --> G["执行方法体"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
六、self 与 cls 在继承中的区别
继承是理解 self 和 cls 的重要场景。
在继承体系中,父类的方法可以被子类继承,但方法执行时接收到的对象取决于调用方式。
1. 继承中的 self
class Animal:
def speak(self):
print("动物发出声音")
class Dog(Animal):
pass
dog = Dog()
dog.speak()
输出:
动物发出声音
虽然 speak() 定义在 Animal 中,但调用它的实例是 dog。
因此,self 指向 Dog 的实例。
进一步验证:
class Animal:
def show_type(self):
print(type(self).__name__)
class Dog(Animal):
pass
dog = Dog()
dog.show_type()
输出:
Dog
这说明继承的方法仍然可以操作子类实例。
2. 继承中的 cls
class Animal:
@classmethod
def show_class(cls):
print(cls.__name__)
class Dog(Animal):
pass
Animal.show_class()
Dog.show_class()
输出:
Animal
Dog
这里:
Animal.show_class()绑定Animal。Dog.show_class()绑定Dog。
虽然类方法定义在父类中,但通过子类调用时,cls 会指向子类。
这使得类方法能够根据实际调用的类执行不同逻辑。
3. 使用 cls 实现多态式实例创建
类方法常用于实现工厂方法。
class Person:
def __init__(self, name):
self.name = name
@classmethod
def create_guest(cls):
return cls("Guest")
class Employee(Person):
def __init__(self, name):
super().__init__(name)
self.role = "employee"
person = Person.create_guest()
employee = Employee.create_guest()
print(type(person).__name__)
print(type(employee).__name__)
print(employee.name)
print(employee.role)
输出:
Person
Employee
Guest
employee
关键代码:
return cls("Guest")
这里没有写死 Person("Guest"),而是使用 cls 创建对象。
因此,当子类继承这个类方法并调用时,创建出来的对象就是子类实例。
这是一种非常实用的继承设计方式。
七、self、cls 与静态方法的区别
除了实例方法和类方法,Python 还有静态方法。
静态方法通过 @staticmethod 装饰器定义,不会自动绑定实例或类对象。
class Calculator:
def add(self, a, b):
return a + b
@classmethod
def describe(cls):
return f"当前类:{cls.__name__}"
@staticmethod
def multiply(a, b):
return a * b
三种方法的区别:
| 方法类型 | 第一个参数 | 自动绑定对象 | 主要用途 |
|---|---|---|---|
| 实例方法 | self |
实例 | 操作实例状态 |
| 类方法 | cls |
类 | 操作类级别状态或创建实例 |
| 静态方法 | 无固定要求 | 不绑定 | 组织与类逻辑相关的独立函数 |
调用示例:
calculator = Calculator()
print(calculator.add(2, 3))
print(Calculator.describe())
print(Calculator.multiply(2, 3))
输出:
5
当前类:Calculator
6
1. 实例方法适合什么场景
当方法需要访问或修改实例属性时,使用实例方法。
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
deposit() 必须知道当前操作的是哪个账户,因此需要 self。
2. 类方法适合什么场景
当方法需要访问类属性、根据当前类创建实例或实现替代构造方式时,使用类方法。
class User:
def __init__(self, name):
self.name = name
@classmethod
def from_dict(cls, data):
return cls(data["name"])
user = User.from_dict({"name": "Alice"})
print(user.name)
from_dict() 不需要已有实例,但需要知道当前类是什么,因此使用 cls。
3. 静态方法适合什么场景
当方法与类的业务领域相关,但既不需要访问实例状态,也不需要访问类状态时,可以使用静态方法。
class User:
@staticmethod
def validate_email(email):
return "@" in email
print(User.validate_email("alice@example.com"))