代碼示例:
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方法的類中是粗制濫造的。任何優雅的解決方案?
uj5u.com熱心網友回復:
可能有更優雅的方法,但是你可以在__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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380223.html
上一篇:在React中為模型使用傳統的Javascript類
下一篇:PythonOOP的問題
