Hello i have designed a maze and i want to draw a path between the cells as the 'person' moves from one cell to the next.
So each time i move the cell a line is drawn
Also i am using the graphics module
The graphics module is an object oriented library
Im importing
from graphics import*
from maze import*
my circle which is my cell
center = Point(15, 15)
c = Circle(center, 12)
c.setFill('blue')
c.setOutline('yellow')
c.draw(win)
p1 = Point(c.getCenter().getX(), c.getCenter().getY())
this is my loop
if mazez.blockedCount(cloc)> 2:
mazez.addDecoration(cloc, "grey")
mazez[cloc].deadend = True
c.move(-25, 0)
p2 = Point(p1.getX(), p1.getY())
line = graphics.Line(p1, p2)
cloc.col = cloc.col - 1
Now it says getX not defined every time i press a key is this because of p2???
This is the most important bits in the module for this part
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master, width=width, height=height)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
if autoflush: _root.update()
def __checkOpen(self):
if self.closed:
raise GraphicsError("window is closed")
def setCoords(self, x1, y1, x2, y2):
"""Set coordinates of window to run from (x1,y1) in the
lower-left corner to (x2,y2) in the upper-right corner."""
self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
def plot(self, x, y, color="black"):
"""Set pixel (x,y) to the given color"""
self.__checkOpen()
xs,ys = self.toScreen(x,y)
self.create_line(xs,ys,xs+1,ys, fill=color)
self.__autoflush()
def plotPixel(self, x, y, color="black"):
"""Set pixel raw (independent of window coordinates) pixel
(x,y) to color"""
self.__checkOpen()
self.create_line(x,y,x+1,y, fill=color)
self.__autoflush()
def draw(self, graphwin):
if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
self.canvas = graphwin
self.id = self._draw(graphwin, self.config)
if graphwin.autoflush:
_root.update()
def move(self, dx, dy):
"""move object dx units in x direction and dy units in y
direction"""
self._move(dx,dy)
canvas = self.canvas
if canvas and not canvas.isClosed():
trans = canvas.trans
if trans:
x = dx/ trans.xscale
y = -dy / trans.yscale
else:
x = dx
y = dy
self.canvas.move(self.id, x, y)
if canvas.autoflush:
_root.update()
class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = x
self.y = y
def _draw(self, canvas, options):
x,y = canvas.toScreen(self.x,self.y)
return canvas.create_rectangle(x,y,x+1,y+1,options)
def _move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
def clone(self):
other = Point(self.x,self.y)
other.config = self.config.copy()
return other
def getX(self): return self.x
def getY(self): return self.y
def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()
def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self.p2.y = self.p2.y + dy
def getP1(self): return self.p1.clone()
def getP2(self): return self.p2.clone()
def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
You might try this from an interactive Python shell:
>>> import graphics
>>> help(graphics.Circle)
That should tell you what attributes Circle does have.
You're trying to use getX() and getY() as free-standing FUNCTIONS:
p2 = Point(getX(), getY())
Note that you're calling them as bare names, not qualified names -- therefore, as functions, not as methods.
And yet the docs you quote say they're methods -- therefore, they must be called as part of qualified names ("after a dot"...!-) and before the dot must be an instance of Point.
Presumably, therefore, you need p1.getX() and p1.getY() instead of the bare names you're using. p1.getX is a qualified name (i.e., one with a dot) and it means "method or attribute getX of object p1.
This is really super-elementary Python, and I recommend you first study the official Python tutorial or other even simpler introductory documents before you try making or modifying applications in Python.
I don't know how maze solves the puzzle, so I am going to assume it works like a generator, yielding the next move for the circle to make. Something to this effect:
while not this_maze.solved():
next_position = this_maze.next()
my_circle.move(next_position)
Then all you need to do is keep track of the current circle position and the previous circle position.
prev_position = this_maze.starting_point
while not this_maze.solved():
next_position = this_maze.next()
my_circle.clear()
draw_trail(prev_position, next_position)
my_circle.draw_at(next_position)
prev_position = next_position
Obviously, changing this in something compatible with your framework is left up to you. dir(), help() and reading the libraries' source will all help you.
Related
I have to generate the Sierpinski Triangle using a 2d point class and tkinter canvas.The midpt function is essentially going to take input from a randomly chosen vertex and the last plotted midpoint. You can choose any vertices to plot the first midpoint. The points also need to be instances of the 2d point class. I desperately need help because I can't seem to figure this out. Here is what the output is supposed to look like.
This is what I have done so far, but it is not using the 2d point class to generate the triangle.
import math
from fractions import Fraction
from random import randrange
from Tkinter import *
# the 2D point class
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# Mutators and Accessors
#property
def x(self):
return self._x
#x.setter
def x(self, value):
self._x = value
#property
def y(self):
return self._y
#y.setter
def y(self, value):
self._y = value
# String function
def __str__(self):
floatX = float(str(self.x))
floatY = float(str(self.y))
return "({},{})".format(floatX, floatY)
# Distance function
def dist(self, other):
distance = math.sqrt(((self.x - other.x)**2)+((self.y - other.y)**2))
return "{}".format(distance)
# Midpoint function
def midpt(self, other):
x0 = float(str(((self.x + other.x))))/2
y0 = float(str(((self.y + other.y)/2)))
return Point(x0, y0)
# the coordinate system class: (0,0) is in the top-left corner
# inherits from the Canvas class of Tkinter
class ChaosGame(Canvas):
def __init__(self, master):
Canvas.__init__(self, master, bg = "white")
self.pack(fill = BOTH, expand = 1)
def plotPoints(self, triangle, NumberPoints):
x0, y0 = WIDTH / 2, HEIGHT / 2
direction = center
for i in range(NumberPoints):
point = randrange(len(triangle))
direction = triangle[point]
x0 = (direction[0] + x0) / 2
y0 = (direction[1] + y0) / 2
color = direction[1]
self.plot(x0, y0)
self.plotV(5, 510)
self.plotV(290, 5)
self.plotV(590, 510)
def plot(self, x, y):
POINT_COLORS=["black"]
RADIUS = 0
color = POINT_COLORS
self.create_oval(x, y, x+2, y+2, outline = color, fill = color)
def plotV(self, x, y):
POINT_COLORS=["red"]
RADIUS = 3
color = POINT_COLORS
self.create_oval(x, y, x+RADIUS*2, y+RADIUS*2, outline = color, fill = color)
##########################################################
# ***DO NOT MODIFY OR REMOVE ANYTHING BELOW THIS POINT!***
# the default size of the canvas is 600x520
WIDTH = 600
HEIGHT = 520
# the number of points to plot
NumberPoints = 50000
# the vertices
A = (5, 510)
B = (290, 5)
C = (590, 510)
triangle = (A, B, C)
center = (WIDTH/2, HEIGHT/2)
# create the window
window = Tk()
window.geometry("{}x{}".format(WIDTH, HEIGHT))
window.title("2D Points...Plotted")
# create the chaos game as a Tkinter canvas inside the window
s = ChaosGame(window)
# plot some random points
s.plotPoints(triangle, NumberPoints)
# wait for the window to close
window.mainloop()
The problem was that you were duplicating the Point-based code in the midpt() method in your plotPoints() method, but for tuples instead of Points. Since the triangle is handed to us as a list of tuples, we convert that to a list of Points, and modify our plot() method to accept a Point, and run the whole plotPoints() method in terms of Points:
from random import choice
from Tkinter import *
class Point(object):
''' a 2D point class '''
def __init__(self, x=0, y=0):
self.x = float(x)
self.y = float(y)
# Mutators and Accessors
#property
def x(self):
return self._x
#x.setter
def x(self, value):
self._x = float(value)
#property
def y(self):
return self._y
#y.setter
def y(self, value):
self._y = float(value)
# String function
def __str__(self):
return "({},{})".format(self.x, self.y)
# Midpoint function
def midpt(self, other):
x0 = (self.x + other.x) / 2
y0 = (self.y + other.y) / 2
return Point(x0, y0)
class ChaosGame(Canvas):
''' Plotting class that inherits from Canvas class of Tkinter '''
VERTEX_RADIUS = 3
VERTEX_COLORS = ["red"]
POINT_RADIUS = 1
POINT_COLORS = ["black"]
def __init__(self, master):
Canvas.__init__(self, master, bg="white")
self.pack(fill=BOTH, expand=1)
def plotPoints(self, triangle, NumberPoints):
point = Point(WIDTH / 2, HEIGHT / 2)
deltoid = [Point(x, y) for x, y in triangle] # tuples -> Points
for _ in range(NumberPoints):
point = point.midpt(choice(deltoid))
self.plot(point)
for vertex in deltoid:
self.plotV(vertex)
def plot(self, point):
radius = self.POINT_RADIUS
color = self.POINT_COLORS
x, y = point.x, point.y
self.create_oval(x, y, x + radius*2, y + radius*2, outline=color, fill=color)
def plotV(self, vertex):
radius = self.VERTEX_RADIUS
color = self.VERTEX_COLORS
x, y = vertex.x, vertex.y
self.create_oval(x, y, x + radius*2, y + radius*2, outline=color, fill=color)
The stuff beyond:
##########################################################
# ***DO NOT MODIFY OR REMOVE ANYTHING BELOW THIS POINT!***
not duplicated here. I also dealt with some whackiness in your Point methods in the way that they insisted on converting numbers to strings and back to numbers, e.g.:
x0 = float(str(((self.x + other.x))))/2
Instead doing:
x0 = (self.x + other.x) / 2
and forcing self.x to be a float when the Point is created.
I am trying to model a simple solar system in Tkinter using circles and moving them around in canvas. However, I am stuck trying to find a way to animate them. I looked around and found the movefunction coupled with after to create an animation loop. I tried fidgeting with the parameters to vary the y offset and create movement in a curved path, but I failed while trying to do this recursively or with a while loop. Here is the code I have so far:
import tkinter
class celestial:
def __init__(self, x0, y0, x1, y1):
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
sol_obj = celestial(200, 250, 250, 200)
sx0 = getattr(sol_obj, 'x0')
sy0 = getattr(sol_obj, 'y0')
sx1 = getattr(sol_obj, 'x1')
sy1 = getattr(sol_obj, 'y1')
coord_sol = sx0, sy0, sx1, sy1
top = tkinter.Tk()
c = tkinter.Canvas(top, bg='black', height=500, width=500)
c.pack()
sol = c.create_oval(coord_sol, fill='black', outline='white')
top.mainloop()
Here's something that shows one way to do what you want using the tkinter after method to update both the position of the object and the associated canvas oval object. It uses a generator function to compute coordinates along a circular path representing the orbit of one of the Celestial instances (named planet_obj1).
import math
try:
import tkinter as tk
except ImportError:
import Tkinter as tk # Python 2
DELAY = 100
CIRCULAR_PATH_INCR = 10
sin = lambda degs: math.sin(math.radians(degs))
cos = lambda degs: math.cos(math.radians(degs))
class Celestial(object):
# Constants
COS_0, COS_180 = cos(0), cos(180)
SIN_90, SIN_270 = sin(90), sin(270)
def __init__(self, x, y, radius):
self.x, self.y = x, y
self.radius = radius
def bounds(self):
""" Return coords of rectangle surrounding circlular object. """
return (self.x + self.radius*self.COS_0, self.y + self.radius*self.SIN_270,
self.x + self.radius*self.COS_180, self.y + self.radius*self.SIN_90)
def circular_path(x, y, radius, delta_ang, start_ang=0):
""" Endlessly generate coords of a circular path every delta angle degrees. """
ang = start_ang % 360
while True:
yield x + radius*cos(ang), y + radius*sin(ang)
ang = (ang+delta_ang) % 360
def update_position(canvas, id, celestial_obj, path_iter):
celestial_obj.x, celestial_obj.y = next(path_iter) # iterate path and set new position
# update the position of the corresponding canvas obj
x0, y0, x1, y1 = canvas.coords(id) # coordinates of canvas oval object
oldx, oldy = (x0+x1) // 2, (y0+y1) // 2 # current center point
dx, dy = celestial_obj.x - oldx, celestial_obj.y - oldy # amount of movement
canvas.move(id, dx, dy) # move canvas oval object that much
# repeat after delay
canvas.after(DELAY, update_position, canvas, id, celestial_obj, path_iter)
top = tk.Tk()
top.title('Circular Path')
canvas = tk.Canvas(top, bg='black', height=500, width=500)
canvas.pack()
sol_obj = Celestial(250, 250, 25)
planet_obj1 = Celestial(250+100, 250, 15)
sol = canvas.create_oval(sol_obj.bounds(), fill='yellow', width=0)
planet1 = canvas.create_oval(planet_obj1.bounds(), fill='blue', width=0)
orbital_radius = math.hypot(sol_obj.x - planet_obj1.x, sol_obj.y - planet_obj1.y)
path_iter = circular_path(sol_obj.x, sol_obj.y, orbital_radius, CIRCULAR_PATH_INCR)
next(path_iter) # prime generator
top.after(DELAY, update_position, canvas, planet1, planet_obj1, path_iter)
top.mainloop()
Here's what it looks like running:
I have two classes (one called 'Point' one called 'PointConector'), both of which inherits 'Frame' (Im not sure If I need to but was seeing if it helped)
When I move the Point (mouse Enter/Leave) and drag the point around, I want to fire off an event for 'PointConnector' (which is a line thats joins the twp points) to pick up the event and redraw the line with the new position of the point.
If I use the event_generate from the canvas object and bind also from the canvas object then the event is picked up, but the object that is passed is the canvas object, not the Point object.
If I fire the event_generate from the Point object (which is inherited from Frame) then the event is ignored
I need the bind event to have the Widget field set to the 'Point' that generated the event. ie I need to have a handle to the point that fired the event. So the Field 'Widget' in the event should be the Point object that is being handled, not the canvas.
from tkinter import Tk, Canvas,Frame
class pointConnector(Frame):
point1 = None
point2 = None
connector = None
def __init__(self,canvas, point1,point2):
super(pointConnector,self).__init__(canvas)
self.point1 = point1
self.point2 = point2
self.canvas = canvas
p1 = self.canvas.translatePoint((self.point1.x,self.point1.y))
p2 = self.canvas.translatePoint((self.point2.x,self.point2.y))
self.connector = canvas.create_line(p1[0], p1[1], p2[0], p2[1],fill='red',state="hidden", width =2)
self.canvas.bind("<<foo>>",self.dummy)
def dummy(self,event):
print("Virtual Event Data: {}".format(event))
def show(self):
self.canvas.itemconfig(self.connector,state="normal")
class screen(Canvas):
width =0
height=0
cY = 0
cX = 0
items =[]
dragItem = None
mouseOverItem = None
def setScreenSize(self,width,height):
self.height = height
self.width = width
self.cX = int(width/2)
self.cY = int(height/2)
def __init__(self,root, unit,width,height):
super(screen,self).__init__(root,width=width,height=height)
self.root = root
self.width = width
self.height = height
self.setScreenSize(width,height)
self.tag_bind('DRAG_OBJECT','<ButtonPress-1>',self.onStartDrag)
self.tag_bind('DRAG_OBJECT','<ButtonRelease-1>',self.onEndDrag)
self.tag_bind('DRAG_OBJECT','<B1-Motion>',self.onDrag)
self.bind("<Configure>", self.configure)
def addObject(self,object):
self.items.append(object)
def findObject(self,tags):
for item in self.items:
if str(item.id) in tags:
return item
return None
def onStartDrag(self,event):
self.dragItem= self.find_closest(event.x,event.y)
wt = self.gettags(self.dragItem)
self.dragItem = self.findObject(wt)
def onEndDrag(self,event):
self.dragItem = None
def onDrag(self,event):
self.dragItem.move(event.x,event.y)
def draw(self):
# Draw array of items
for o in self.items:
o.show()
def translateX(self,x):
return (x + self.cX)
def translateY(self,y):
return (y + self.cY)
def translatePoint(self,pointxy):
return (self.translateX(pointxy[0]),self.translateY(pointxy[1]))
class point(Frame):
state = "normal"
x : int
y : int
def setPoint(self,x,y):
self.x = x
self.y = y
def __init__(self,canvas,x,y,radius,ObjectName):
super(point,self).__init__(canvas)
self.x = x
self.y = y
self.radius = radius
self.canvas = canvas
self.ObjectName= ObjectName
self.id = None
self.create_point()
def create_point(self):
x = self.canvas.translateX(self.x)
y = self.canvas.translateY(self.y)
self.circle = self.canvas.create_oval(x-self.radius,y-self.radius,x+self.radius,y+self.radius,state=self.state,fill='yellow')
self.text = self.canvas.create_text(x,y,text=self.ObjectName,state=self.state )
self.canvas.itemconfig(self.circle, tags=({"type":"POINT", "name":self.ObjectName},"DRAG_OBJECT"))
self.canvas.itemconfig(self.text, tags=({"type":"POINT", "name":self.ObjectName},"DRAG_OBJECT"))
self.id = {"type":"POINT", "name":self.ObjectName}
def show(self):
newX = self.canvas.translateX(self.x)
newY = self.canvas.translateY(self.y)
self.canvas.itemconfig(self.circle,state='normal')
self.canvas.coords(self.circle,(newX-self.radius,newY-self.radius,newX + self.radius, newY + self.radius))
self.canvas.coords(self.text,(newX,newY))
self.canvas.itemconfig(self.text,state='normal')
self.canvas.tag_raise(self.circle)
self.canvas.tag_raise(self.text)
def hide(self):
self.canvas.itemconfig(self.circle,state='hidden')
self.canvas.itemconfig(self.text,state='hidden')
def move (self,x,y):
delta_x = x- (self.x + self.canvas.cX)
delta_y = y- (self.y + self.canvas.cY)
self.canvas.move(self.circle,delta_x,delta_y)
self.canvas.move(self.text,delta_x,delta_y)
self.x = x - self.canvas.cX
self.y = y - self.canvas.cY
## If I use the canvas object (that is passed in) then the Point object picks up the event, but then I cant tell which 'Point' is begin dragged
#self.canvas.event_generate("<<foo>>",x=self.x,y=self.y,when='now')
## If I generate the event from the Point Object then the Event is lost
self.event_generate("<<foo>>",x=self.x,y=self.y,when='tail')
self.update()
# Start of program
print("Start --->")
tk = Tk()
mainScreen = screen(tk,20,700,700)
mainScreen.pack(fill="both",expand=1)
# Add Point A
pointA = point(mainScreen,0,0,10,"A",)
mainScreen.addObject(pointA)
# Add Point B
pointB = point(mainScreen,20,20,10,"B")
mainScreen.addObject(pointB)
LineA = pointConnector(mainScreen,pointA,pointB)
mainScreen.addObject(LineA)
mainScreen.draw()
tk.mainloop()
I am trying to model a simple solar system in Tkinter using circles and moving them around in canvas. However, I am stuck trying to find a way to animate them. I looked around and found the movefunction coupled with after to create an animation loop. I tried fidgeting with the parameters to vary the y offset and create movement in a curved path, but I failed while trying to do this recursively or with a while loop. Here is the code I have so far:
import tkinter
class celestial:
def __init__(self, x0, y0, x1, y1):
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
sol_obj = celestial(200, 250, 250, 200)
sx0 = getattr(sol_obj, 'x0')
sy0 = getattr(sol_obj, 'y0')
sx1 = getattr(sol_obj, 'x1')
sy1 = getattr(sol_obj, 'y1')
coord_sol = sx0, sy0, sx1, sy1
top = tkinter.Tk()
c = tkinter.Canvas(top, bg='black', height=500, width=500)
c.pack()
sol = c.create_oval(coord_sol, fill='black', outline='white')
top.mainloop()
Here's something that shows one way to do what you want using the tkinter after method to update both the position of the object and the associated canvas oval object. It uses a generator function to compute coordinates along a circular path representing the orbit of one of the Celestial instances (named planet_obj1).
import math
try:
import tkinter as tk
except ImportError:
import Tkinter as tk # Python 2
DELAY = 100
CIRCULAR_PATH_INCR = 10
sin = lambda degs: math.sin(math.radians(degs))
cos = lambda degs: math.cos(math.radians(degs))
class Celestial(object):
# Constants
COS_0, COS_180 = cos(0), cos(180)
SIN_90, SIN_270 = sin(90), sin(270)
def __init__(self, x, y, radius):
self.x, self.y = x, y
self.radius = radius
def bounds(self):
""" Return coords of rectangle surrounding circlular object. """
return (self.x + self.radius*self.COS_0, self.y + self.radius*self.SIN_270,
self.x + self.radius*self.COS_180, self.y + self.radius*self.SIN_90)
def circular_path(x, y, radius, delta_ang, start_ang=0):
""" Endlessly generate coords of a circular path every delta angle degrees. """
ang = start_ang % 360
while True:
yield x + radius*cos(ang), y + radius*sin(ang)
ang = (ang+delta_ang) % 360
def update_position(canvas, id, celestial_obj, path_iter):
celestial_obj.x, celestial_obj.y = next(path_iter) # iterate path and set new position
# update the position of the corresponding canvas obj
x0, y0, x1, y1 = canvas.coords(id) # coordinates of canvas oval object
oldx, oldy = (x0+x1) // 2, (y0+y1) // 2 # current center point
dx, dy = celestial_obj.x - oldx, celestial_obj.y - oldy # amount of movement
canvas.move(id, dx, dy) # move canvas oval object that much
# repeat after delay
canvas.after(DELAY, update_position, canvas, id, celestial_obj, path_iter)
top = tk.Tk()
top.title('Circular Path')
canvas = tk.Canvas(top, bg='black', height=500, width=500)
canvas.pack()
sol_obj = Celestial(250, 250, 25)
planet_obj1 = Celestial(250+100, 250, 15)
sol = canvas.create_oval(sol_obj.bounds(), fill='yellow', width=0)
planet1 = canvas.create_oval(planet_obj1.bounds(), fill='blue', width=0)
orbital_radius = math.hypot(sol_obj.x - planet_obj1.x, sol_obj.y - planet_obj1.y)
path_iter = circular_path(sol_obj.x, sol_obj.y, orbital_radius, CIRCULAR_PATH_INCR)
next(path_iter) # prime generator
top.after(DELAY, update_position, canvas, planet1, planet_obj1, path_iter)
top.mainloop()
Here's what it looks like running:
Having the following code:
class Point:
'class that represents a point in the plane'
def __init__(self, xcoord=0, ycoord=0):
''' (Point,number, number) -> None
initialize point coordinates to (xcoord, ycoord)'''
self.x = xcoord
self.y = ycoord
def setx(self, xcoord):
''' (Point,number)->None
Sets x coordinate of point to xcoord'''
self.x = xcoord
def sety(self, ycoord):
''' (Point,number)->None
Sets y coordinate of point to ycoord'''
self.y = ycoord
def get(self):
'''(Point)->tuple
Returns a tuple with x and y coordinates of the point'''
return (self.x, self.y)
def move(self, dx, dy):
'''(Point,number,number)->None
changes the x and y coordinates by dx and dy'''
self.x += dx
self.y += dy
def __repr__(self):
'''(Point)->str
Returns canonical string representation Point(x, y)'''
return 'Point('+str(self.x)+','+str(self.y)+')'
class Rectangle(Point):
def __init__(self,bottom_left,top_right,color):
self.get = bottom_left
self.get = top_right
self.color = color
def get_bottom_left(self,bottom_left):
print ()
r1 = Rectangle(Point(0,0), Point(1,1), "red")
r1.get_bottom_left()
I want to be able to print "Point(0,0)" by calling self__rep__(self) from class Point from the method get_bottom_left, but I just have no idea how. I know how to use inheritance if the functions have the same name, but in this case I am stuck and it is a requirement for the child function to have the method names it has. If it looks that I am just looking for the answer, I would like the response to just explain me a similar case of this application please!
When I do the following:
class Rectangle(Point):
def __init__(self,bottom_left,top_right,color):
self.get = bottom_left
self.get = top_right
self.color = color
def get_bottom_left(self,bottom_left):
print (self.bottom_left)
I get: get_bottom_left() missing 1 required positional argument: 'bottom_left'
As mentioned in the comment, Rectangle should contain Point instances and not inherit Point. If you change Rectangle class as shown below, you'll see the expected result:
class Rectangle():
def __init__(self, bottom_left, top_right, color):
self.bottom_left = bottom_left
self.top_right = top_right
self.color = color
def get_bottom_left(self):
print self.bottom_left