需要在运行时在我的 class
/object
中添加一个 proc,以使用内部变量和其他私有(private)类方法执行一些代码(无法提供更多详细信息)。
想知道如何实现这一点,所以得出了我自己的解决方案(作为当前答案提供)。有没有更好的方法来做同样的事情?
最佳答案
感谢@user2357112。 以下代码有效(从调试中断期间启动的调试评估器对话框执行):
class someClass(object):
def __init__(self):
self.element1 = '1'
def pre_defined_method (self):
print('in pre_defined_method - element1: {}'.format(self.element1))
def new_object_bound_method (self):
print('in new_object_bound_method - element1: {}'.format(self.element1))
from types import MethodType
obj = someClass()
setattr(obj, 'new_object_bound_method',
MethodType(new_object_bound_method, obj))
obj.pre_defined_method()
obj.new_object_bound_method()
obj.pre_defined_method()
try:
obj2 = someClass()
obj2.new_object_bound_method()
except Exception as e:
print('"new_object_bound_method" is only bound to instance "obj" and not class "someClass"')
print(e)
def new_class_bound_method(self):
print('in new_class_bound_method - element1: {}'.format(self.element1))
someClass.new_class_bound_method = \
MethodType(new_class_bound_method, None, someClass)
obj2.new_class_bound_method()
输出是:
in pre_defined_method - element1: 1
in new_object_bound_method - element1: 1
in pre_defined_method - element1: 1
"new_object_bound_method" is only bound to instance "obj" and not class "someClass"
'someClass' object has no attribute 'new_object_bound_method'
in new_class_bound_method - element1: 1
关于python - 如何在 Pycharm 的调试 session 中断期间向 python 类/对象添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54084944/