user3157264
user3157264

Reputation: 119

Printing a string and executing functions inside a class [Python]

For my school assignment we have to write a program to simmulate a traffic light. I've got the program working the only problem is that the code is a bit of a mess because I don't know how to use classes properly. And the documentation just confuses me (a bit of a noob).

So I just copied the function I wanted to change an variable in multiple times and changed the variables by hand. I know it's possible to do this with classes and just make an instance of this class with the right variable but I can seem to get it to work. Here is a small example in "pseudo code" of what I want to achieve.

This code is a timer that times for how long the traffic light is on. I want to make a class that can accept a side (left,right,front,back) and print this string so I dont have to copy the code and manualy enter the side. But I can just make an instance with one of the sides.

import time

class trafficlight_timer:
    def __init__(self, side1):
        self.side = side1

    def trafficlight(self, side1):
        s = 0
        b = 5
        t_max = 10
        print self.side,  "is green"
        if b > t_max:
            b = t_max
        while s <= 60:
            time.sleep(1)
            s += 1
            if s == b:
                print self.side, "is red"
                print self.side, "was green for %d seconds." % s
                print ""
                s = 65
    trafficlight()

instance_left = trafficlight_timer('left')

If someone could point out to me how this should be done I would be very grateful. Many thanks in advance!

Upvotes: 3

Views: 4827

Answers (1)

brianmearns
brianmearns

Reputation: 9967

What's wrong with what you have? I didn't try to run it, but it looks mostly fine to me, except that you wouldn't normally call trafficlight() from inside the class body (may not even be legal syntax, I'm not sure).

import time

class trafficlight_timer:
    def __init__(self, side1):
        self.side = side1

    def trafficlight(self):
        s = 0
        b = 5
        t_max = 10
        print self.side,  "is green"
        if b > t_max:
            b = t_max
        while s <= 60:
            time.sleep(1)
            s += 1
            if s == b:
                print self.side, "is red"
                print self.side, "was green for %d seconds." % s
                print ""
                s = 65

instance_left = trafficlight_timer('left')
instance_left.trafficlight()

The only changes I made were to delete trafficlight() from the class body, remove the redundant and unused side1 parameter from the trafficlight function, and call trafficlight() on the instance_left instance. The output looks like this:

left is green
left is red
left was green for 5 seconds.

If that's not what you want, describe in more detail what you expect for the output and what undesirable output you are getting.

Upvotes: 2

Related Questions