Why do you need explicitly have the “self” argument in a Python method?

前端 未结 10 1385
借酒劲吻你
借酒劲吻你 2020-11-22 11:53

When defining a method on a class in Python, it looks something like this:

class MyClass(object):
    def __init__(self, x, y):
        self.x = x
        se         


        
10条回答
  •  耶瑟儿~
    2020-11-22 12:31

    I suggest that one should read Guido van Rossum's blog on this topic - Why explicit self has to stay.

    When a method definition is decorated, we don't know whether to automatically give it a 'self' parameter or not: the decorator could turn the function into a static method (which has no 'self'), or a class method (which has a funny kind of self that refers to a class instead of an instance), or it could do something completely different (it's trivial to write a decorator that implements '@classmethod' or '@staticmethod' in pure Python). There's no way without knowing what the decorator does whether to endow the method being defined with an implicit 'self' argument or not.

    I reject hacks like special-casing '@classmethod' and '@staticmethod'.

提交回复
热议问题