member variable string gets treated as Tuple in Python

让人想犯罪 __ 提交于 2021-02-10 17:55:35

问题


I am currently learning Python with the help of CodeAcademy. My problem may be related to their web application, but my suspicion is I am just wrong on a very fundamental level here.

If you want to follow along I am referring to CodeAcademy.com -> Python -> Classes 6/11

My code looks like this:

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

What is suppossed to happen, is, that every member variable of the object my_car gets printed on screen. I was expecting that like condition, color and model would be treated as a string, but instead get treated as a Tuple.

The output looks like this:

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

Which leads to the validation failing, because CA expects "silver" but the code returns ('silver',).

Where is the error in my code on this?


回答1:


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



回答2:


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

Remove them and you'll get it without a tuple




回答3:


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.



来源:https://stackoverflow.com/questions/66061148/python-explicitly-define-object-attribute-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!