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

前端 未结 10 1382
借酒劲吻你
借酒劲吻你 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:51

    As explained in self in Python, Demystified

    anything like obj.meth(args) becomes Class.meth(obj, args). The calling process is automatic while the receiving process is not (its explicit). This is the reason the first parameter of a function in class must be the object itself.

    class Point(object):
        def __init__(self,x = 0,y = 0):
            self.x = x
            self.y = y
    
        def distance(self):
            """Find distance from origin"""
            return (self.x**2 + self.y**2) ** 0.5
    

    Invocations:

    >>> p1 = Point(6,8)
    >>> p1.distance()
    10.0
    

    init() defines three parameters but we just passed two (6 and 8). Similarly distance() requires one but zero arguments were passed.

    Why is Python not complaining about this argument number mismatch?

    Generally, when we call a method with some arguments, the corresponding class function is called by placing the method's object before the first argument. So, anything like obj.meth(args) becomes Class.meth(obj, args). The calling process is automatic while the receiving process is not (its explicit).

    This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like this) but I strongly suggest you not to. Using names other than self is frowned upon by most developers and degrades the readability of the code ("Readability counts").
    ...
    In, the first example self.x is an instance attribute whereas x is a local variable. They are not the same and lie in different namespaces.

    Self Is Here To Stay

    Many have proposed to make self a keyword in Python, like this in C++ and Java. This would eliminate the redundant use of explicit self from the formal parameter list in methods. While this idea seems promising, it's not going to happen. At least not in the near future. The main reason is backward compatibility. Here is a blog from the creator of Python himself explaining why the explicit self has to stay.

提交回复
热议问题