如何在Pycharm的调试会话中断期间向python类/对象添加方法?

时间:2019-01-08 03:46:29

标签: python python-3.x pycharm

需要在运行时在我的class / object中添加proc以使用内部变量和其他私有类方法(无法提供更多详细信息)来执行一些代码。

想知道如何实现这一目标,所以得出了我自己的解决方案(作为当前答案提供)。有没有更好的方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

感谢@ 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