3
class Foo():
    def __init__(self):
        pass

    def makeInstanceAttribute(oops):
        oops.x = 10

f = Foo()
f.makeInstanceAttribute()
print(f.x)

and it's printing 10, how does it work? Why oops has same effect of being self?

mzoz
  • 1,273
  • 1
  • 14
  • 28

2 Answers2

2

self is just a convention. It can be named anyway you want. What actually is passed to the function as the first argument is the object instance. Consider this code:

class A(object):
    def self_test(self):
        print self

    def foo(oops):
        print oops

>>> a = A()
>>> a.self_test()
<__main__.A object at 0x03CB18D0>
>>> a.foo()
<__main__.A object at 0x03CB18D0>
>>> 

This question is probably related to yours, you might find it helpful.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
2

Quoting the Python documentation:

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

L3viathan
  • 26,748
  • 2
  • 58
  • 81