我正在创建一个汽车类,您可以在其中创建自己的汽车,但是它不起作用

“尝试创建一个可以创建自己的汽车的程序。问题是我收到一条我不理解的错误消息。该程序本身应该可以创建汽车并放入年份模型。我可能已经结束了我的头在这里,因为我以前从未使用过类函数”

“错误消息” “第1行,在Car类中:” ”,第13行,在Car print中(“我现在已经获得了我的“,a.getYear(),”年模型“)” “ NameError:未定义名称'a'”

class Car:

    def __init__(self, a=0):
        self.Year= a

    def getYear(self):
        return self.Year

    def setYear(self, a):
        self.year = a
        return

    print("i have now goten my  ",a.getYear(),"year model")
评论
玩火自焚
玩火自焚

a is a variable right ? Then you are using it inside a function, wich will not work if you don't put a global. How does it work ? Exemple :

a = "hello"
def print():
    print(a)
print()

输出应该是“ hello”,对吗?但是该函数就像第一个脚本中的第二个脚本,因此您需要告诉他去从函数中搜索可评估的脚本。因此:

a = "hello"
def print():
    global a
    print(a)
print()

输出为“ hello”,因为现在a是一个全局变量,将对主脚本和函数都起作用!

点赞
评论
[绿茶]
[绿茶]

您有几个错误...尝试此代码..它应该可以工作:

class Car:

    def __init__(self):
        a = 0
        self.Year= a

    def getYear(self):
        return self.Year

    def setYear(self, a):
        self.Year = a
        print("i have now goten my  ", self.getYear(),"year model")
        #return self.Year

bmw = Car()
bmw.setYear(10)

这应该给您:

i have now goten my   10 year model
点赞
评论
爱旳偏执
爱旳偏执

Because a is a local variable if you want to use your class globally assign your class to a variable and do your job, example;

class Car:

    def __init__(self, a=0):
        self.Year= a

    def getYear(self):
        return self.Year

    def setYear(self, a):
        self.year = a
        return

    someVariable = Car()

    print("i have now goten my  ",someVariable.getYear(),"year model")
点赞
评论