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.

1

4 Answers 4

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.

1
  • 2
    >self.x is an attribute of the Point class< better: > self.x is an attribute of a Point class instance<
    – warvariuc
    Jul 15, 2012 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.

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

3
  • 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. Jul 15, 2012 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, 2012 at 10:49
  • My mistake, I should clarify that I have checkout those questions. Jul 15, 2012 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

3
  • 3
    Mind adding even a little bit of explanation as to how this applies? Jan 17, 2015 at 22:38
  • Explain everything. It is unclear how it applies to the question, especially for a user who doesn't understand the topic well Jan 18, 2015 at 13:41
  • This 'self' topic has been 'explained' by many others , so try some other explanation if you don't like mine.
    – nick k
    Jan 18, 2015 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.