在Python中,成员变量字符串被视为元组
我目前在CodeAcademy的帮助下学习Python。我的问题可能与他们的web应用程序有关,但我怀疑我只是在一个非常基本的层面上错了 如果你想继续,我指的是codeaccademy.com->Python->Classes 6/11 我的代码如下所示:在Python中,成员变量字符串被视为元组,python,class,Python,Class,我目前在CodeAcademy的帮助下学习Python。我的问题可能与他们的web应用程序有关,但我怀疑我只是在一个非常基本的层面上错了 如果你想继续,我指的是codeaccademy.com->Python->Classes 6/11 我的代码如下所示: class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model, s
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model,
self.color = color,
self.mpg = mpg
my_car = Car("DeLorean", "silver", 88)
print my_car.model
print my_car.color
print my_car.mpg
print my_car.condition
('DeLorean',) #Tuple
('silver',) #Tuple
88
new #String
None
支持的情况是,对象my_car
的每个成员变量都打印在屏幕上。我希望像条件
、颜色
和模型
一样被视为一个字符串,而不是被视为一个元组
输出如下所示:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model,
self.color = color,
self.mpg = mpg
my_car = Car("DeLorean", "silver", 88)
print my_car.model
print my_car.color
print my_car.mpg
print my_car.condition
('DeLorean',) #Tuple
('silver',) #Tuple
88
new #String
None
这导致验证失败,因为CA需要“silver”,但代码返回('silver',)
我的代码中的错误在哪里?在您的
\uuuu init\uuuu
中,您有:
self.model = model,
self.color = color,
这就是定义元组的方式。将行更改为
self.model = model
self.color = color
没有逗号:
>>> a = 2,
>>> a
(2,)
vs
在构造函数中,这些属性后面有一个逗号
删除它们,您将得到它,而不需要元组是的,您必须从实例变量中删除逗号<代码>从self.model=model到self.model=model 很高兴看到,您正在使用类变量概念,
“
condition
”是类变量,“self.model
”、“self.color
”、“self.mpg
”是实例变量。就是这样-只是在C#和Python之间的翻译中丢失了。干杯一旦锁被打开,Accept就会出现。所以,很简单。但我还是迷路了,这是我第二次遇到这个问题,为什么我如此愚蠢,我很感谢你的提问。我教Python和后面的逗号问题。这是我第一次看到有人犯下这个错误的真实例子!谢谢。是的,很难忘记一个人所知道的关于其他语言的一切。我经常写object=newclass
,只是因为我习惯了它。我想在接下来的几周里,我会经常结结巴巴地讨论语法mashup。这些不是属性,只是属性。