1

I'm confused in bellowing code:

class Point():
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

I do not understand what those two x in code self.x = x mean.

dda
  • 6,030
  • 2
  • 25
  • 34
stardiviner
  • 1,090
  • 1
  • 22
  • 33
  • possible duplicate of [Python 'self' explained](http://stackoverflow.com/questions/2709821/python-self-explained) – user2864740 Jan 17 '15 at 22:58

4 Answers4

11

self.x is an attribute of the Point class. So if p is an instance of the Point class, then p.x is the self.x you see above (self being a reference to the class you are defining). The second x is the parameter passed at init time def __init__(self, x=0, y=0):. Note that it defaults to zero in case you don't pass anything.

dda
  • 6,030
  • 2
  • 25
  • 34
  • 2
    >`self.x` is an attribute of the Point class< better: > `self.x` is an attribute of a Point class instance – warvariuc Jul 15 '12 at 10:35
7

The first x is an attribute of self, while the second comes into the method as its second argument.

You could write it as:

class Point():
    def __init__(self, new_x=0, new_y=0):
        self.x = new_x
        self.y = new_y

and see which belongs to which one.

eumiro
  • 207,213
  • 34
  • 299
  • 261
2

First read this question and answer: What is the purpose of self?. To your question, the first self.x is an attribute of self and the second x is an argument you are getting in your constructor for Point

Community
  • 1
  • 1
zenpoy
  • 19,490
  • 9
  • 60
  • 87
  • I did a search before I ask, and I have seen that question and answer, I found I still can not solve my confuse. that's why I ask. Actually some of explains in that answers is difficult to understand for me. But that answers are good for me. thanks. – stardiviner Jul 15 '12 at 10:46
  • I didn't imply you didn't make any research, I just pointed out a good starting point for you to read, so that my answer would make sense without having to explain what `self` is... cheers. – zenpoy Jul 15 '12 at 10:49
  • My mistake, I should clarify that I have checkout those questions. – stardiviner Jul 15 '12 at 14:10
-2
class Employee:
   def __init__(self, name, salary):
       self.name = name
       self.salary = salary    # self ? ? ?

   def displayEmployee(self):
       salary  =  -69 
       print self.name, self.salary,salary    # self ? ? ?

run:

emp1 = Employee("nick", 2000)

emp1.displayEmployee()      # self ! ! !

output:

nick 2000 -69

'self' explained! : self.salary = 2000 , salary = -69

nick k
  • 1
  • 2