成员变量 string 在 Python 中被视为 Tuple

我目前正在 CodeAcademy 的帮助下学习 Python。我的问题可能与他们的 Web 应用程序有关,但我怀疑我只是在一个非常基本的层面上错了。

如果你想继续下去,我指的是 CodeAcademy. com-> Python-> Class 6/11

我的代码是这样的:

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

应该发生的是,对象 my_car的每个成员变量都会在屏幕上打印出来。我期望像 conditioncolormodel一样被当作一个字符串来处理,而不是被当作一个 Tuple来处理。

输出如下:

('DeLorean',) #Tuple
('silver',) #Tuple
88
new #String
None

这将导致验证失败,因为 CA 期望“ silver”,但是代码返回 ('silver',)

我的代码错误在哪里?

16379 次浏览

In your __init__, you have:

    self.model = model,
self.color = color,

which is how you define a tuple. Change the lines to

    self.model = model
self.color = color

without the comma:

>>> a = 2,
>>> a
(2,)

vs

>>> a = 2
>>> a
2

You've got a comma after those attributes in your constructor function.

Remove them and you'll get it without a tuple

yes, you have to remove comma from instance variables. from self.model = model, to self.model = model

Nice to see, you are using Class variable concept, "condition" is class variable and "self.model", "self.color", "self.mpg" are instance variables.