全局名称未在类中定义

时间:2014-04-29 05:01:45

标签: python class object

我遇到一个错误,说明此程序中未定义全局名称。我已经尝试了所有我能想到的调试这个,但我仍然没有运气。我是面向对象编程的新手,所以任何修复它的帮助都是值得赞赏的。

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 __init__(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 self.__speed+5

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

1 个答案:

答案 0 :(得分:1)

您使用accelerate方法在代码中出现缩进错误。这是正确的代码:还请查看我在您的代码中做出的所有其他编辑(评论):

WORKING DEMO

    def main():

    ford=Car(2008,'mustang')       #mustang should be a string (in '')
    count=0

    for count in range(5):
        ford.accelerate()
        count+=1
        print("The speed is : "+str(ford.get_speed()))   #you must cast the int as str

    for count in range(5):
        ford.brake()
        count-=1
        print("The speed is : "+str(ford.get_speed()))   #you must cast the int as str

class Car:

    def __init__(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):
        self.__speed += 5           #you should actually increment your speed instead of returning it

    def brake(self):
        self.__speed -= 5           #you should actually decrement your speed instead of returning it


main()           #Call the main() method to make the script actually run