【问题标题】:Python: Is it possible to override/extend an instance method of one class when it is used in another class?Python:当一个类在另一个类中使用时,是否可以覆盖/扩展一个类的实例方法?
【发布时间】:2020-11-16 16:07:09
【问题描述】:

我正在计划一个 Python 项目。我将拥有使用其他类实例的类。是否可以从另一个类中覆盖/扩展方法,如下所示:

class Foo:

    a = Bar()
    b = Bar()
    c = Bar()

class Baz:

    x = Bar()
    y = Bar()
    z = Bar()

class Qux:

    p = Bar()
    q = Bar()
    r = Bar()

class Bar:

    def __init__(self):
        pass

    def do_something():
        # Thing to do

Baz.x.do_something() # Does the same thing 
Qux.p.do_something() # Does the same thing

Foo.a.do_something() # Does something slightly different

稍有不同的行为将取决于 Foo 类实例,因此我无法在 Bar 类中为其创建新方法。 注意 Bar 的大部分行为都是一样的。我只想在 Foo.a.do_something() 中多做一步

【问题讨论】:

    标签: python class methods overriding instance


    【解决方案1】:

    不是以干净的方式。总的来说,这似乎是个坏主意。你怎么知道do_something 的行为如何?这将是一场调试噩梦。

    如果do_something 需要做一些不同的事情,子类Bar 并在每个子类中以不同的方式实现它。

    class Bar:    
        def do_something():
            # Does something
    
    class Bar2(Bar):    
        def do_something():
            # Does something else
    

    【讨论】:

    • 谢谢。感觉是个坏主意,你是对的。我只是想不出还有什么办法。我会试一试你的建议。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多