MLhacker
MLhacker

Reputation: 1512

How do you get arguments in python class to receive values?

I'd like to create a class that draws a line using the Turtle module.

class Line(object):

    def __init__(self, coordinates):
        self.start_x = 0
        self.start_y = 0
        self.end_x = coordinates[0]
        self.end_y = coordinates[1]

    def drawing(self, pensize, pencolor):
        self.pensize = pensize
        self.color = pencolor

def main():
    turtle.setup(700,400, startx = 0, starty = 0)
    line = Line()
    turtle.done()
main()

How should I get the instant of the line class to receive coordinates on where the line needs to be drawn out to?

I already recognize that I can just use functions, but, for the sake of understanding how class works, I'd like to implement class to draw lines. The inspiration comes from a project I'm self-learning. The link to the project is:

http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/08_ClassDesign/TurtleSnowPeople/Project10.pdf

Upvotes: 0

Views: 119

Answers (1)

Wayne Werner
Wayne Werner

Reputation: 51907

Python, unlike certain other languages, does not require that you create classes. It's possible, of course, but not necessary.

The simplest way to draw a line, of course, would to be to simply draw the line:

import turtle


def main():
    turtle.setup(700, 700, startx=0, starty=0)  
    turtle.penup()
    turtle.goto(13, 42)
    turtle.pendown()
    turtle.goto(42, 13)
    turtle.done()


if __name__ == '__main__':
    main()

But obviously, you want to extract this out so you can repeat the operation without having to repeat those four lines. The simplest way to do that is to create a function. Since you have reference to the turtle module, all you need to pass in is the start and end coordinates:

import turtle


def draw_line(startx, starty, endx, endy):
    turtle.penup()
    turtle.goto(startx, starty)
    turtle.pendown()
    turtle.goto(endx, endy)


def main():
    turtle.setup(700, 700, startx=0, starty=0)  
    draw_line(13, 42, 42, 13)
    turtle.done()


if __name__ == '__main__':
    main()

Alternatively you could use something like namedtuple:

import turtle
from collections import namedtuple


Point = namedtuple('Point', ('x', 'y'))


def draw_line(start, end):
    turtle.penup()
    turtle.goto(start.x, start.y)
    turtle.pendown()
    turtle.goto(end.x, end.y)


def main():
    turtle.setup(700, 700, startx=0, starty=0)

    start = Point(13, 42)
    end = Point(42, 13)
    draw_line(start, end)

    turtle.done()


if __name__ == '__main__':
    main()

But if you just really love classes you can still use them. Just put the same code into your class that you would've put anywhere else.

Upvotes: 1

Related Questions