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

标签 python python-3.x pycharm

需要在运行时在我的 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/

相关文章:

python-3.x - OpenCV 通过矩阵比较值进行错误级别分析

python - 语法无效 : Azure CLI with Python

python - 使用 xvfb + PyCharm + vagrant 设置测试

windows - 无法在 Python (Windows) 中安装镜像包 - 需要 zlib

python - TensorFlow 的 Print 或 K.print_tensor 不会在损失函数中打印中间张量

python - 为什么Python中的属性查找是这样设计的(优先链)?

python - django.core.exceptions.ImproperlyConfigured

python - 如何绘制复杂的多边形?

python - 将 csv 导入 python 的确切文件夹

python - 如何在使用 Pycharm + Docker 测试项目时在 Python 库包上进行开发?