python 动态绑定,动态绑定方法到python中的类实例

这篇博客探讨了如何在Python中动态地为类添加方法,并确保该方法能够访问到类的实例变量。通过使用`types.MethodType`和`__import__`函数,实现了在类初始化时从外部模块加载并绑定方法。示例展示了如何从`moduleB.py`导入`meth2`方法,并将其绑定到`ClassA`的实例上,使得`calling_method`能正确调用`meth2`并访问到类的`a`和`b`变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Let's say that I have a class defined in moduleA.py which I want to add a method to, using some sort of loader method that takes a the name of a second module and the method defined there that should be bound

class ClassA(object):

def __init__(self,config):

super(ClassA, self).__init__()

self.a = 1

self.b = 2

self.meth1 = self. bind_method(config)

def bind_method(self,config):

# load method

def calling_method():

return self.meth1()

where the method defined in moduleB.py looks something like:

def meth2(self):

return self.a + self.b

The point being that I want to be able to write meth2 to be able to access class variables of ClassA once it is bound. This way, when you would have something like:

from moduleA import ClassA

A = ClassA()

aout = A.calling_method()

Calling A.calling_method() properly calls the method defined in moduleB.py.

I've seen this sort of binding done in answers on SO after ClassA is instantiated using types.MethodType, but I haven't been able to dig up how to bind inside the class definition so that it is done internally when the class is instantiated.

Any suggestions on what should go in the bind_method method would be much appreciated.

解决方案import sys

import types

def getobj(astr):

"""

getobj('scipy.stats.stats') returns the associated module

getobj('scipy.stats.stats.chisquare') returns the associated function

"""

try:

return globals()[astr]

except KeyError:

try:

return __import__(astr, fromlist=[''])

except ImportError:

modname, _, basename = astr.rpartition('.')

if modname:

mod = getobj(modname)

return getattr(mod, basename)

else:

raise

class ClassA(object):

def __init__(self, methpath):

super(ClassA, self).__init__()

self.a = 1

self.b = 2

self.meth1 = types.MethodType(getobj(methpath), self)

a = ClassA('moduleB.meth2')

print(a.meth1())

# 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值