【问题标题】:Python: How do you decorate methods in child classes using a method in the parent class?Python:如何使用父类中的方法装饰子类中的方法?
【发布时间】:2022-01-16 06:40:22
【问题描述】:

代码示例:

class Parent:
    # something here that says that the function "foo" always starts in print("bar")

class Son(Parent):
    def foo(self):
        pass

class Daughter(Parent):
    def foo(self):
        print("q")


Son().foo() # prints "bar"
Daughter().foo() # prints "bar" then "q"

我尝试使用@super.func,尽管在每个以Parent 为父级并具有foo 方法的类中复制粘贴它是伪劣的。有什么优雅的解决方案吗?

【问题讨论】:

    标签: python class oop decorator


    【解决方案1】:

    可能还有更优雅的方法,但是可以在__init_subclass__钩子中装饰子类的方法

    def bar_printer(f):
        def wrapper(*args, **kwargs):
            print('bar')
            return f(*args, **kwargs)
    
        return wrapper
    
    
    class Parent:
    
        def foo(self):
            pass
    
        def __init_subclass__(cls, **kwargs):
            cls.foo = bar_printer(cls.foo)
    
    
    class Son(Parent):
        def foo(self):
            pass
    
    
    class Daughter(Parent):
        def foo(self):
            print("q")
    
    son = Son()
    daughter = Daughter()
    
    son.foo()
    daughter.foo()
    

    输出:

    bar
    bar
    q
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2021-02-12
      • 2021-09-28
      • 2013-05-23
      • 2020-11-24
      • 2014-09-06
      • 1970-01-01
      相关资源
      最近更新 更多