0

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?

1
  • It's assuming p1 and p2 are instances of your Point class, not integers. Rather than L1(7,2), you should use L1(P1, P2) in your example. Commented Mar 16, 2022 at 4:09

1 Answer 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

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

3 Comments

@itsrxmmy...But what is the value being accessed.?
since self is the object, whatever follows is an attribute. so for __init__ of the Line class, self.p1 refers to the p1 attribute
I read the question wrong. (in the slope function) self refers to the object, p2 refers to the attribute of that object, and y is the attribute of the p2 attribute. its nested pretty much.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.