“尝试创建一个可以创建自己的汽车的程序。问题是我收到一条我不理解的错误消息。该程序本身应该可以创建汽车并放入年份模型。我可能已经结束了我的头在这里,因为我以前从未使用过类函数”
“错误消息” “第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 :输出应该是“ hello”,对吗?但是该函数就像第一个脚本中的第二个脚本,因此您需要告诉他去从函数中搜索可评估的脚本。因此:
输出为“ hello”,因为现在a是一个全局变量,将对主脚本和函数都起作用!
您有几个错误...尝试此代码..它应该可以工作:
这应该给您:
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;