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.
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.
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.
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.
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
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