While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 7 22:44:31 CET 2008

On Fri, 07 Mar 2008 09:49:58 -0800, Krishna wrote:

> I am more interested in knowing about the first argument ('self'), what
> does it hold to allow the evaluation of the method, take the example you
> gave, 'self.a' as Rvalue inside the method, how and why is this allowed,

"self" is treated as an argument like any other argument, except that 
when you call a method on an instance Python automatically provides the 
self for you.

Consider the following piece of code:

>>> class Parrot(object):
...     def squawk(self, n):
...         return "spam " * n
>>> instance = Parrot()
>>> instance.squawk(3)
'spam spam spam '
>>> Parrot.squawk(instance, 3)
'spam spam spam '

In the first call, I call the squawk() method from the instance, and 
Python automatically fills in the self argument.

In the second call, I call the squawk() method from the class. Since the 
class doesn't know what instance I'm using, I have to manually provide 
the self argument.

But inside the method, self is just a name in a namespace, like any other 
name. It's not special. You can do anything you like to it. You can even 
re-assign to it, or delete it:

>>> class Spam(object):
...     def spam(self):
...             print "I am", self
...             self = "foo"
...             print "Now I am", self
>>> x = Spam()
>>> x.spam()
I am <__main__.Spam object at 0xb7f5192c>
Now I am foo
>>> x
<__main__.Spam object at 0xb7f5192c>

> when the same 'self.a' is not allowed as the default argument,

It isn't that self.a is "not allowed". Python doesn't contain any code 
that says "if the default value contains "self", raise an error. You can 
prove that for yourself:

>>> def foo(x=self):
...     return x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'self' is not defined
>>> self = 2
>>> def foo(x=self):
...     return x
>>> foo()

> considering the fact that I have already specified 'self' as first
> argument, only after whose evaluation, I believe would the next
> statement (k = self.a, in def func(self, k = self.a) ) gets evaluated

You believe wrong. You've already been told that the function default 
"k=self.a" is evaluated when the method is compiled, not at runtime. 
Since "self" doesn't exist at compile time, it is an error.

There is no way to create a reference to a class instance before the 
class is even defined.


More information about the Python-list mailing list