Consider the following class:
class Foo(object):
def bar(self):
print(self)
In Python 2 (2.7.13), calling bar()
as a class method raises an exception:
>>> Foo.bar('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead)
>>> Foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead)
When bar()
is called as an instance method it recognizes self
as the instance when called without arguments
>>> Foo().bar('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes exactly 1 argument (2 given)
>>> Foo().bar()
<__main__.Foo object at 0x10a8e1a10>
In Python 3 (3.6.0), when calling bar()
as a class method, the first argument is accepted as self
:
>>> Foo.bar('hello')
hello
>>> Foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() missing 1 required positional argument: 'self'
Calling bar()
as an instance method works as in Python 2
>>> Foo().bar('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 1 positional argument but 2 were given
>>> Foo().bar()
<__main__.Foo object at 0x104ab34a8>