'Multiple classes in Python
I am learning OOPS in Python. I encountered this piece of code during my course.
class Point(object):
def __init__(self,x,y):
self.x=x
self.y=y
class Line(object):
def __init__(self,p1,p2):
self.p1=p1
self.p2=p2
def slope(self):
return (self.p2.y - self.p1.y)/ (self.p2.x-self.p1.x)
Let's say for Point class I have two instances P1(11,6) and P2(12,3). For class Line, I have one object L1(7,2). What does it mean that self.p2.y? What value would be accessed here?
I have looked at many places but couldn't find this concept?
Solution 1:[1]
self refers to the object of that class. the variables after the . operator are attributes
you can use something other than self, but its good practice to use self.
so for P1, self refers to the P1 object.
theres also a version of self for classes (cls) but thats for class methods
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | itsrxmmy |
