问题
I have the following snippet:
from decorators import before_save
class User(Model):
def before_save(self):
pass
@before_save
def meth(self):
pass
It seems that when I try to decorate meth
, it "uses" the instance method before_save
, not the imported decorator. How can I still declare an instance method with the same name as a decorator and still be able to properly use both of them?
Shouldn't the decorator work as expected? How is it possible to refer to the before_save
instance method just as before_save
, without any reference to its class?
回答1:
You can try the following
import decorators
# omitted
@decorators.before_save
def meth(self):
pass
I wanted to use a one-liner but run into this.
回答2:
You can change the import name:
from decorators import before_save as before_save_decorator
class User(Model):
def before_save(self):
pass
@before_save_decorator
def meth(self):
pass
That should let you use both.
回答3:
Or you could define before_save
method after:
from decorators import before_save
class User(Model):
@before_save
def meth(self):
pass
def before_save(self):
pass
But this is not the best solution, because it's not obvious what's going on here, and you can forget about later.
来源:https://stackoverflow.com/questions/28994359/use-decorator-with-same-name-as-an-instance-method