Reputation: 85
I was trying to program an application using pygame which can plot lines. The code-snippet is as shown below-
grapher.py
some code...
x = 500
class graph():
def drawgrid(step, t = 1):
for i in range(0, x//step):
pygame.draw.line(win, (0, 0, 255), (i*step, 0), (i*step, y), t)
pygame.draw.line(win, (0, 0, 255), (0, i*step), (x, i*step), t)
pygame.display.update()
The graph.drawgrid()
just draws a grid, with each line spaced out evenly by some pixels(value stored in step
variable).
When I run graph.drawgrid()
in the same python file(grapher.py
), it works as expected.
But now, I want to run the function in a different file(main.py
). The code snippet is below-
main.py
import grapher
import pygame
x = 500
draw = grapher.graph()
win = pygame.display.set_mode((x, y))
pygame.display.set_caption("Graph")
run = True
while(run):
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw.drawgrid(50)
pygame.quit()
I call the function, and it gets called, but also within that process, the function(graph.drawgrid()
) when called, throws the following error -
for i in range(0, 500//step):
TypeError: unsupported operand type(s) for //: 'int' and 'graph'
And, when I change for i in range(0, x//step):
to for i in range(0, x//int(step)):
It throws this error now-
for i in range(0, 500//int(step)):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'graph'
I'm not sure why this is happening, can anyone tell where I'm going wrong and the solution to this?
Upvotes: 2
Views: 332
Reputation: 191
You are missing the self
argument in your drawgrid function.
class graph:
def drawgrid(self, step, t = 1):
for i in range(0, x//step):
pygame.draw.line(win, (0, 0, 255), (i*step, 0), (i*step, y), t)
pygame.draw.line(win, (0, 0, 255), (0, i*step), (x, i*step), t)
pygame.display.update()
The first argument of every function in your class is always the instance the method is called on. In your case you dont have an argument in the function definition for that, so it gets assigned to step.
Edit: Here's a site explaining it in more detail.
Upvotes: 3
Reputation: 371
The class in grapher.py
and its methods should be declared the following way:
class graph:
def drawgrid(self, step, t = 1): # add self parameter
Upvotes: 2