python —— types.MethodType —— 函数绑定

1. 将函数绑定到类对象上

from types import MethodType

class Student:
    def __init__(self, name):
        self._name = name
        
def get_name(obj):
    print(f"Name is {obj._name}")
    
s = Student("Fengjie")
print(s._name)
s.get_name = MethodType(get_name, s)
s.get_name()
print("-----------------")
print(s.__dict__)
print("-----------------")
s2 = Student("Bala Bala")
s2.get_name()



运行效果:

image







2. 将绑定到类上,实现类方法的效果

from types import MethodType

class Student:
    def __init__(self, name):
        self._name = name
        
def get_object(obj):
    print(f"object is {obj}")
    
Student.get_object = MethodType(get_object, Student)
s = Student("Fengjie")
s.get_object()
print("-----------------")
print(s.__dict__)
print("-----------------")
s2 = Student("Bala Bala")
s2.get_object()

运行效果:

image



上面代码等价于:

from types import MethodType

class Student:
    def __init__(self, name):
        self._name = name
    @classmethod
    def get_object(cls):
        print(f"object is {cls}")
    
s = Student("Fengjie")
s.get_object()
print("-----------------")
print(s.__dict__)
print("-----------------")
s2 = Student("Bala Bala")
s2.get_object()

运行效果:

image




参考:

https://zhuanlan.zhihu.com/p/668280709


posted on 2025-12-13 21:23  Angry_Panda  阅读(2)  评论(0)    收藏  举报

导航