目录
绑定方法
Python 中的方法分为三种,绑定行为各不相同:
| 方法类型 | 装饰器 | 绑定对象 | 首个参数 |
|---|---|---|---|
| 实例方法 | 无 | 实例(self) | self |
| 类方法 | @classmethod | 类(cls) | cls |
| 静态方法 | @staticmethod | 无绑定 | 无 |
简单来说
我们先定义一个类
class Student():
school='sysu'
name='cvcvc'
age=22
def show_info(self):
print(self.school)
print(self.name)
print(self.age)
def add(x,y):
c=x+y
return c
再定义一个对象
stu_obj1=Student()
在调用对象方法时,第一步是将对象传入对象方法,如下图所示:

但这一步是非显式的,而且每次调用时自动执行
如果类内定义的函数没有参数,那么在类对象方法调用时,就会报错,比如下方的调用
stu_obj1=Student()
print(Student.add(12,13))
print(stu_obj1.add(12,13))
25
TypeError Traceback (most recent call last)
Cell In[13], line 20
16 # stu_obj1.show_info()
17 # Student.show_info(stu_obj1)
19 print(Student.add(12,13))
---> 20 print(stu_obj1.add(12,13))
TypeError: add() takes 2 positional arguments but 3 were given
在Student类的add()函数定义中没有参数,因此在类对象调用时会导致报错
举例说明
实例方法
class Student():
school='sysu'
name='cvcvc'
age=22
def show_info(self):
print(self.school)
print(self.name)
print(self.age)
def add(x,y):
c=x+y
return c
查看类和类对象的函数地址
stu_obj1=Student()
print('类show_info函数:',Student.show_info)
print('类add函数:',Student.add)
print('对象show_info函数:',stu_obj1.show_info)
print('对象add函数:',stu_obj1.add)
类show_info函数: <function Student.show_info at 0x0000019703AB04C0>
类add函数: <function Student.add at 0x0000019703AB03A0>
对象show_info函数: <bound method Student.show_info of <__main__.Student object at 0x0000019702099430>>
对象add函数: <bound method Student.add of <__main__.Student object at 0x0000019702099430>>
可以看到类对象的函数中显示bound method,即绑定方法
stu_obj1=Student()
stu_obj1.show_info()
Student.show_info(stu_obj1)
sysu
cvcvc
22
sysu
cvcvc
22
这里使用类方法和类对象方法的输出是相同的
stu_obj1=Student()
print(Student.add(12,13))
print(stu_obj1.add(12,13))
25
TypeError Traceback (most recent call last)
Cell In[13], line 20
16 # stu_obj1.show_info()
17 # Student.show_info(stu_obj1)
19 print(Student.add(12,13))
---> 20 print(stu_obj1.add(12,13))
TypeError: add() takes 2 positional arguments but 3 were given
在Student类的add()函数定义中没有参数,因此在类对象调用时会导致报错
类方法的绑定行为
类方法通过 @classmethod 装饰器定义,始终绑定到类本身
class Cat:
@classmethod
def meow(cls): # 类方法
print(f"{cls.__name__} 在喵喵叫!")
# 通过类访问 → 绑定方法(自动传入 cls)
Cat.meow() # 输出:Cat 在喵喵叫!
# 通过实例访问 → 仍绑定到类
cat = Cat()
cat.meow() # 输出:Cat 在喵喵叫!
静态方法的无绑定行为
静态方法通过 @staticmethod 装饰器定义,不会自动绑定任何参数。
class MathUtils:
@staticmethod
def add(a, b): # 静态方法
return a + b
# 通过类或实例调用 → 直接传参
MathUtils.add(1, 2) # 返回 3
obj = MathUtils()
obj.add(3, 4) # 返回 7
11万+

被折叠的 条评论
为什么被折叠?



