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

前端 未结 3 750
猫巷女王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: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.

提交回复
热议问题