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.

Sign up to request clarification or add additional context in comments.

1 Comment

>self.x is an attribute of the Point class< better: > self.x is an attribute of a Point class instance<
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.

Comments

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 Comments

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.
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.
My mistake, I should clarify that I have checkout those questions.
-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 Comments

Mind adding even a little bit of explanation as to how this applies?
Explain everything. It is unclear how it applies to the question, especially for a user who doesn't understand the topic well
This 'self' topic has been 'explained' by many others , so try some other explanation if you don't like mine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.