Use decorator with same name as an instance method

假装没事ソ 提交于 2019-12-25 01:47:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!