دنبال کننده ها

۱۳۹۶ دی ۱۳, چهارشنبه

python 3.x - How to correctly inherit methods from class to class?

[ad_1]



I'm trying to build a "polygon" object, composed of four "point" objects which I have already defined. The point object has a method that allows me to shift the points in the x and y-axis.



I want to use this method in my polygon class, in order to shift all four points. I do not know very well how the inheritance works and I don't understand how I could shift the points when their parameters are contained in a tuple.



(this is for a homework, so I have to stick to point class)



Any insights would be much appreciated, I'm trying to understand classes better. Thanks.



class Point: 
def __init__(self,x=0,y=0):
''' x and y are int or float '''
self.x = x
self.y = y
def __repr__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
def distance(self,other):
return ((self.x-other.x)**2+(self.y-other.y)**2)**0.5
def shift(self,dx,dy):
self.x += dx
self.y += dy


#

class Polygon(Point): #Polygon class inherits Point class
def __init__(self, points):
Point.__init__(self)
self.points = points

def __repr__(self):
return str(self.points)

def shift(self,dx,dy):
for i in self.points:
Point.shift(self,dx,dy)

return self.points



a=Point(0,0)
b=Point(0,2)
c=Point(2,2)
d=Point(2,0)
e=Point(1,-1)

P=Polygon((a,b,c,d,e))
print(P)

P.shift(1,0)
print(P)



[ad_2]

لینک منبع