Can a method be used as either a staticmethod or instance method?

后端 未结 4 1793
遇见更好的自我
遇见更好的自我 2021-01-18 20:08

I\'d like to be able to do this:

class A(object):
    @staticandinstancemethod
    def B(self=None, x, y):
        print self is None and \"static\" or \"ins         


        
4条回答
  •  天涯浪人
    2021-01-18 20:51

    Since you'd like the static method case to be used to create a new class anyway, you'd best just make it a normal method and call it at the end of the __init__ method.

    Or, if you don't want that, create a separate factory function outside the class that will instantiate a new, empty object, and call the desired method on it.

    There probably are ways of making exactly what you are asking for, but they will wander through the inner mechanisms of Python, be confusing, incompatible across python 2.x and 3.x - and I can't see a real need for it.

提交回复
热议问题