class ABC:
def xyz(self):
print "in xyz"
obj = ABC()
print obj.xyz()
output : in xyz
here self
is not given as parameter while calling xyz
with obj
.
class ABC:
def xyz(self):
print "in xyz"
obj = ABC()
print obj.xyz()
output : in xyz
here self
is not given as parameter while calling xyz
with obj
.
That's because self
is, by default, the instance itself. obj.xyz()
is equivalent to ABC.xyz(obj)
.
The first argument of every class method, including __init__
, is always a reference to the current instance of the class.
By convention, this argument is always named self
.
In the __init__
method, self refers to the newly created object; in other instance methods, it refers to the instance whose method was called. Although you need to specify self
explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically.
Technically, this is what happens:
obj.xyz
obj
has no attribute named xyz
obj
's class (ABC
) for an attribute named xyz
, which it does haveABC.xyz
is a function, so then it "wraps" it into a "instance method". Basically, ABC.xyz
is a function with one parameter (self
), so the "instance method" is a function with one less parameter from the original function (no parameters in this case), which remembers the object obj
. And if you call this "instance method", it passes it onto ABC.xyz
, with the first argument being obj
, the rest of the arguments being the argument to the bound method.obj.xyz
evaluates to this instance methodABC.xyz
, with the remembered instance (obj
) as the first argument.Here are the relevant parts from the language reference (scroll from here):
Class instances
A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object, it is transformed into an instance method object whose
__self__
attribute is the instance. [...]
and
Instance methods
[...]
When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its
__self__
attribute is the instance, and the method object is said to be bound. The new method’s__func__
attribute is the original function object.[...]
When an instance method object is called, the underlying function (
__func__
) is called, inserting the class instance (__self__
) in front of the argument list. For instance, whenC
is a class which contains a definition for a functionf()
, andx
is an instance ofC
, callingx.f(1)
is equivalent to callingC.f(x, 1)
.[...]
In the backend of the code obj.xyz()
. The parameter returned is object(obj) itself that means ABC.xyz(obj)