Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

class - member variable string gets treated as Tuple in Python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...