Search code examples
pythonself

What do these two 'x' mean in this Python code: self.x = x?


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.


Solution

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