Nested attribute in python

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) #which value is being accessed with self.p2.y

What is the meaning of self.p2.y? What value is being accessed?
P1= Point(3,4) (x,y)
P2= Point(5,6) (x,y)
L1= Line(2,3) (p1,p2)

Do you have any hunches which one? You might add some print calls to the slope method to get better idea what that’s going to be:

print(self.p2)
print(self.p2.y)

self.p2 will access 3.
For the second case, it generates an error that int object has no attribute y.

@sanity Have a look.

3 doesn’t have y attribute indeed, however is it intended to instantiate Line object with two integers?

The way these classes are structured, The Line class would always take two instances of the Point class as argument. You can easily specify the type of the coming arguments to the constructor as below.

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Line(object):
    def __init__(self,  p1: Point , p2: Point):
        self.p1 = p1
        self.p2 = p2
        
    def slope(self):
        return (self.p2.y - self.p1.y) / (self.p2.x - self.p1.x)

So this would be the correct way of instantiating the classes.

point1 = Point(x=3, y=4)
point2 = Point(x=5, y=6)

L1 = Line(p1=point1, p2=point2)

# now you can call the slope method on `Line` class instance like

L1.slope()

In the above example,
self.p2.y would be the y value of point2 instance which is 6 in this case.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.