Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?

前端 未结 4 1442
既然无缘
既然无缘 2020-11-29 18:35

I\'m a Java developer who\'s toyed around with Python on and off. I recently stumbled upon this article which mentions common mistakes Java programmers make when they pick u

4条回答
  •  一生所求
    2020-11-29 19:23

    This is not really an answer, but rather a lengthy comment:

    Even more puzzling is that this code:

            class A:
                def foo(x):
                    print(x)
            A.foo(5)
    

    Fails as expected in Python 2.7.3 but works fine in 3.2.3 (although you can't call the method on an instance of A, only on the class.)

    I'll try to explain what happens here.

    This is, strictly speaking, an abuse of the "normal" instance method protocol.

    What you define here is a method, but with the first (and only) parameter not named self, but x. Of course you can call the method in an instance of A, but you'll have to call it like this:

    A().foo()
    

    or

    a = A()
    a.foo()
    

    so the instance is given to the function as first argument.

    The possibility to call regular methods via the class has always been there and works by

    a = A()
    A.foo(a)
    

    Here, as you call the method of the class rather than on the instance, it doesn't get its first parameter given automaticvally, but you'll have to provide it.

    As long as this is an instance of A, everything is ok. Giving it something else is IMO an abuse of the protocol, and thus the difference between Py2 and Py3:

    In Py2, A.foo gets transformed to an unbound method and thus requires its first argument be an instance of the class it "lives" in. Calling it with something else will fail.

    In Py3, this check has been dropped and A.foo is just the original function object. So you can call it with everything as first argument, but I wouldn't do it. The first parameter of a method should always be named self and have the semantics of self.

提交回复
热议问题