当前位置: 首页 > news >正文

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

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

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

from types import MethodTypeclass Student:def __init__(self, name):self._name = namedef 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










参考:

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