【问题标题】:How to modify class's method behaviour? Python, class belongs to library that can't be changed如何修改类的方法行为? Python,类属于无法更改的库
【发布时间】:2013-06-08 07:52:15
【问题描述】:

有一些用 Python (2.x) 编写的库。它的代码不能更改。 lib里面有A类。我需要修改A::method()的行为。还有很多其他类:B 类、C 类等等(它们也都属于 lib)。他们都以某种方式使用 A 类 - 无论如何。这意味着我不能继承类 A 并覆盖方法 A::method()。

据我所知,应该使用 Python-Decorators-technic。但具体如何?你能展示一些这样的解决方案的样本吗???

【问题讨论】:

    标签: python-2.7 python-decorators


    【解决方案1】:

    你试过了吗:

    from lib import A
    
    def my_method(instance, *args, **kwargs):
        some_code_here()
    
    A.method = my_method
    

    【讨论】:

    • 在使用了 10 多年的 C++ 之后,以这样的方式思考有点困难 :) 谢谢! Тhen 我还有一个问题 - Decorator 是干什么用的?
    • 装饰器是一个在返回之前修改另一个函数的函数;这可能也是一个可能的解决方案,但是如果您需要对各种不同的功能重复进行一些修改,那么装饰器是有意义的。
    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多