[英]How to call a function on every method call of an object
我有這個 class:
class DieKlass:
#My attempt using __init__
def __init__(self):
aMethod()
def hello(self):
print ("Hello !")
#Some other file
Def aMethod():
print ("me !")
我希望它在“ob”作為 DieKlass 的實例時得到這樣的結果:
ob.hello()
導致:
me !
Hello !
如何在 DieKlass object 的每個方法調用上調用 aMethod() 而不在 DieKlass 方法體中顯式調用 aMethod?
def aMethod(func):
def function_wrapper(x):
print("Me")
func(x)
return function_wrapper
class DieKlass:
@aMethod
def hello(self):
print("Hello")
您可以在這里找到更多信息: https://www.python-course.eu/python3_decorators.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.