GrapeSoda3
GrapeSoda3

Reputation: 577

Global variable not defined with class

I am really new to object oriented programing and could use a little help on my program. I keep getting global varible not defined error, and I do not know what I am doing wrong. Also, if anyone could offer insight on why you need the "self" defention in the classes and what that actually does that would be great. any help is appreciated.

CODE:

def main():

    ford=Car(2008,mustang)
    count=0

    for count in range(5):
        ford.accelerate()
        count+=1
        print("The speed is : "+ford.get_speed())

    for count in range(5):
        ford.brake()
        count-=1
        print("The speed is : "+ford.get_speed())

class Car:

    def __Car__(self,model,carMake):
        self.__yearModel=model
        self.__make=carMake
        self.__speed=0

    def set_Model(self, model):
        self.__yearModel=model

    def set_Make(self,carMake):
        self.__make=carMake

    def get_Model(self):
        return self.__yearModel 

    def get_speed(self):
        return self.__speed

    def get_make(self):
        return self.__make

    def accelerate(self):
        return speed+5

    def brake(self):
        return speed-5

Upvotes: 0

Views: 80

Answers (2)

Brad Budlong
Brad Budlong

Reputation: 1785

You have both a problem that you aren't referring to the class attribute __speed and the other is that you are not updating the value of the attribute. You need to change the last to methods as follows:

def accelerate(self):
    self.__speed += 5
    return self.__speed

def brake(self):
    self.__speed -= 5
    return self.__speed

Upvotes: 0

Hunter Larco
Hunter Larco

Reputation: 780

I would guess that the global variable not defined error is coming from these lines

def accelerate(self):
    return speed+5

def brake(self):
    return speed-5

which should be changed to

def accelerate(self):
        return self.__speed+5

def brake(self):
    return self.__speed-5

As for what does self mean? Each time you make a new instance of the Car class, self allows a method inside of the class to know what it belongs to. It is essentially the instance of the car being automatically supplied to each function for ease of use.

Think of it this way. A car needs to know things about itself, such as how much gas it has. But if it cannot find it's own gas tank then it cant figure that out? That's where self is handy. It is your access point to the car instance.

Upvotes: 1

Related Questions