Why is self only a convention and not a real Python keyword?

前端 未结 3 744
猫巷女王i
猫巷女王i 2020-12-11 01:54

As far as I know, self is just a very powerful convention and it\'s not really a reserved keyword in Python. Java and C# have this as a keyword. I really f

相关标签:
3条回答
  • 2020-12-11 02:35

    Guido van Rossum has blogged on why explicit self has to stay: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html

    I believe that post provides some insight into the design decisions behind explicit self.

    0 讨论(0)
  • 2020-12-11 02:42

    Because self is just a parameter to a function, like any other parameter. For example, the following call:

    a = A()
    a.x()
    

    essentially gets converted to:

    a = A()
    A.x(a)
    

    Not making self a reserved word has had the fortunate result as well that for class methods, you can rename the first parameter to something else (normally cls). And of course for static methods, the first parameter has no relationship to the instance it is called on e.g.:

    class A:
        def method(self):
            pass
    
        @classmethod
        def class_method(cls):
            pass
    
        @staticmethod
        def static_method():
            pass
    
    class B(A):
        pass
    
    b = B()
    b.method()        # self is b
    b.class_method()  # cls is B
    b.static_method() # no parameter passed
    
    0 讨论(0)
  • 2020-12-11 02:43

    Because a method is just a function who's first parameter is used to pass the object. You can write a method like this:

    class Foo(object):
        pass
    
    def setx(self, x):
        self.x = x
    
    Foo.setx = setx
    
    foo = Foo()
    foo.setx(42)
    print foo.x    # Prints 42.
    

    Whatever the merit or otherwise of this philosophy, it does result in a more unified notion of functions and methods.

    0 讨论(0)
提交回复
热议问题