<p>When defining a method on a class in Python, it looks something like this:</p>

<pre><code>class MyClass(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
</code></pre>

<p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype.  </p>

<p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>

[{'answer_id': 68320, 'author': 'Ryan', 'author_id': 8819, 'author_profile': 'https://Stackoverflow.com/users/8819', 'pm_score': 6, 'selected': False, 'text': "<p>It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.</p>\n<p>e.g.</p>\n<pre><code>&gt;&gt;&gt; class C:\n...     def foo(self):\n...         print(&quot;Hi!&quot;)\n...\n&gt;&gt;&gt;\n&gt;&gt;&gt; def bar(self):\n...     print(&quot;Bork bork bork!&quot;)\n...\n&gt;&gt;&gt;\n&gt;&gt;&gt; c = C()\n&gt;&gt;&gt; C.bar = bar\n&gt;&gt;&gt; c.bar()\nBork bork bork!\n&gt;&gt;&gt; c.foo()\nHi!\n&gt;&gt;&gt;\n</code></pre>\n<p>It also (as far as I know) makes the implementation of the python runtime easier.</p>\n"}, {'answer_id': 68324, 'author': 'S.Lott', 'author_id': 10661, 'author_profile': 'https://Stackoverflow.com/users/10661', 'pm_score': 8, 'selected': True, 'text': '<p>I like to quote Peters\' Zen of Python.  "Explicit is better than implicit."</p>\n\n<p>In Java and C++, \'<code>this.</code>\' can be deduced, except when you have variable names that make it impossible to deduce.   So you sometimes need it and sometimes don\'t.</p>\n\n<p>Python elects to make things like this explicit rather than based on a rule.  </p>\n\n<p>Additionally, since nothing is implied or assumed, parts of the implementation are exposed.  <code>self.__class__</code>, <code>self.__dict__</code> and other "internal" structures are available in an obvious way.</p>\n'}, {'answer_id': 68329, 'author': 'Flávio Amieiro', 'author_id': 802, 'author_profile': 'https://Stackoverflow.com/users/802', 'pm_score': -1, 'selected': False, 'text': '<p>There is also another very simple answer: according to the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">zen of python</a>, "explicit is better than implicit".</p>\n'}, {'answer_id': 68472, 'author': 'Victor Noagbodji', 'author_id': 10710, 'author_profile': 'https://Stackoverflow.com/users/10710', 'pm_score': 4, 'selected': False, 'text': '<p>Python doesn\'t force you on using "self". You can give it whatever name you want. You just have to remember that the first argument in a method definition header is a reference to the object.</p>\n'}, {'answer_id': 308045, 'author': 'bhadra', 'author_id': 30289, 'author_profile': 'https://Stackoverflow.com/users/30289', 'pm_score': 6, 'selected': False, 'text': '<p>I suggest that one should read <a href="http://neopythonic.blogspot.com/" rel="noreferrer">Guido van Rossum\'s blog</a> on this topic - <a href="http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html" rel="noreferrer">Why explicit self has to stay</a>.</p>\n<blockquote>\n<p>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.</p>\n<p>I reject hacks like special-casing \'@classmethod\' and \'@staticmethod\'.</p>\n</blockquote>\n'}, {'answer_id': 29369904, 'author': 'daole', 'author_id': 1649107, 'author_profile': 'https://Stackoverflow.com/users/1649107', 'pm_score': 2, 'selected': False, 'text': '<p>I think it has to do with PEP 227:</p>\n\n<blockquote>\n  <p>Names in class scope are not accessible.  Names are resolved in the\n  innermost enclosing function scope.  If a class definition occurs in a\n  chain of nested scopes, the resolution process skips class\n  definitions.  This rule prevents odd interactions between class\n  attributes and local variable access.  If a name binding operation\n  occurs in a class definition, it creates an attribute on the resulting\n  class object.  To access this variable in a method, or in a function\n  nested within a method, an attribute reference must be used, either\n  via self or via the class name.</p>\n</blockquote>\n'}, {'answer_id': 31367197, 'author': 'vlad-ardelean', 'author_id': 1037251, 'author_profile': 'https://Stackoverflow.com/users/1037251', 'pm_score': 3, 'selected': False, 'text': '<p>Also allows you to do this: (in short, invoking <code>Outer(3).create_inner_class(4)().weird_sum_with_closure_scope(5)</code> will return 12, but will do so in the craziest of ways.</p>\n\n<pre><code>class Outer(object):\n    def __init__(self, outer_num):\n        self.outer_num = outer_num\n\n    def create_inner_class(outer_self, inner_arg):\n        class Inner(object):\n            inner_arg = inner_arg\n            def weird_sum_with_closure_scope(inner_self, num)\n                return num + outer_self.outer_num + inner_arg\n        return Inner\n</code></pre>\n\n<p>Of course, this is harder to imagine in languages like Java and C#. By making the self reference explicit, you\'re free to refer to any object by that self reference. Also, such a way of playing with classes at runtime is harder to do in the more static languages - not that\'s it\'s necessarily good or bad. It\'s just that the explicit self allows all this craziness to exist.</p>\n\n<p>Moreover, imagine this: We\'d like to customize the behavior of methods (for profiling, or some crazy black magic). This can lead us to think: what if we had a class <code>Method</code> whose behavior we could override or control?</p>\n\n<p>Well here it is:</p>\n\n<pre><code>from functools import partial\n\nclass MagicMethod(object):\n    """Does black magic when called"""\n    def __get__(self, obj, obj_type):\n        # This binds the &lt;other&gt; class instance to the &lt;innocent_self&gt; parameter\n        # of the method MagicMethod.invoke\n        return partial(self.invoke, obj)\n\n\n    def invoke(magic_self, innocent_self, *args, **kwargs):\n        # do black magic here\n        ...\n        print magic_self, innocent_self, args, kwargs\n\nclass InnocentClass(object):\n    magic_method = MagicMethod()\n</code></pre>\n\n<p>And now: <code>InnocentClass().magic_method()</code> will act like expected. The method will be bound with the <code>innocent_self</code> parameter to <code>InnocentClass</code>, and with the <code>magic_self</code> to the MagicMethod instance. Weird huh? It\'s like having 2 keywords <code>this1</code> and <code>this2</code> in languages like Java and C#. Magic like this allows frameworks to do stuff that would otherwise be much more verbose.</p>\n\n<p>Again, I don\'t want to comment on the ethics of this stuff. I just wanted to show things that would be harder to do without an explicit self reference.</p>\n'}, {'answer_id': 36968741, 'author': 'pankajdoharey', 'author_id': 615116, 'author_profile': 'https://Stackoverflow.com/users/615116', 'pm_score': 2, 'selected': False, 'text': '<p>I think the real reason besides "The Zen of Python" is that Functions are first class citizens in Python. </p>\n\n<p>Which essentially makes them an Object. Now The fundamental issue is if your functions are object as well then, in Object oriented paradigm how would you send messages to Objects when the messages themselves are objects ? </p>\n\n<p>Looks like a chicken egg problem, to reduce this paradox, the only possible way is to either pass a context of execution to methods or detect it. But since python can have nested functions it would be impossible to do so as the context of execution would change for inner functions. </p>\n\n<p>This means the only possible solution is to explicitly pass \'self\' (The context of execution).</p>\n\n<p>So i believe it is a implementation problem the Zen came much later.</p>\n'}, {'answer_id': 54510770, 'author': 'mon', 'author_id': 4281353, 'author_profile': 'https://Stackoverflow.com/users/4281353', 'pm_score': 1, 'selected': False, 'text': '<h1>As explained in <a href="https://www.programiz.com/article/python-self-why" rel="nofollow noreferrer">self in Python, Demystified</a></h1>\n\n<blockquote>\n  <p>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. </p>\n</blockquote>\n\n<pre><code>class Point(object):\n    def __init__(self,x = 0,y = 0):\n        self.x = x\n        self.y = y\n\n    def distance(self):\n        """Find distance from origin"""\n        return (self.x**2 + self.y**2) ** 0.5\n</code></pre>\n\n<p>Invocations:</p>\n\n<pre><code>&gt;&gt;&gt; p1 = Point(6,8)\n&gt;&gt;&gt; p1.distance()\n10.0\n</code></pre>\n\n<p><strong>init</strong>() defines three parameters but we just passed two (6 and 8). Similarly distance() requires one but zero arguments were passed. </p>\n\n<p>Why is Python not complaining about <strong>this argument number mismatch</strong>?</p>\n\n<blockquote>\n  <p>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). <strong>The calling process is automatic while the receiving process is not (its explicit).</strong><BR><BR>\n  <strong>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</strong>. 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").\n  <BR>...<BR>\n  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.</p>\n</blockquote>\n\n<p></p>\n\n<blockquote>\n  <h2>Self Is Here To Stay</h2>\n  \n  <p>Many have proposed to <strong>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.</strong> While this idea seems promising, it\'s not going to happen. At least not in the near future. <strong>The main reason is backward compatibility</strong>. Here is a blog from the creator of Python himself explaining why the explicit self has to stay.</p>\n</blockquote>\n'}, {'answer_id': 63481620, 'author': 'Sanmitha Sadhishkumar', 'author_id': 13827419, 'author_profile': 'https://Stackoverflow.com/users/13827419', 'pm_score': 0, 'selected': False, 'text': "<p>The 'self' parameter keeps the current calling object.</p>\n<pre><code>class class_name:\n    class_variable\n    def method_name(self,arg):\n        self.var=arg \nobj=class_name()\nobj.method_name()\n</code></pre>\n<p>here, the self argument holds the object obj. Hence, the statement self.var denotes obj.var</p>\n"}]
['https://Stackoverflow.com/questions/68282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4883/']