Python:如何使用父 class 中的方法修饰子 class 中的方法?
Python: How do you decorate methods in child classes using a method in the parent class?
代码示例:
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
,尽管在每个 class 中复制粘贴它是劣质的,它具有 Parent
作为父级并具有 foo
方法。任何优雅的解决方案?
可能还有更优雅的方法,但是可以在__init_subclass__
hook
中装饰子类的方法
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
代码示例:
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
,尽管在每个 class 中复制粘贴它是劣质的,它具有 Parent
作为父级并具有 foo
方法。任何优雅的解决方案?
可能还有更优雅的方法,但是可以在__init_subclass__
hook
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