Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

member variable string gets treated as Tuple in Python

Tags:

python

class

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?

like image 531
Marco Avatar asked Dec 26 '14 08:12

Marco


People also ask

Why is a string a tuple in Python?

A string is defined and is displayed on the console. The string is split, and every element is converted to an integer, and this operation is applied to every element using the 'map' method. This is again converted to a tuple type. This result is assigned to a value.

How do you convert a tuple to a variable in Python?

Example: Adding Variables to a Tuple using vars() Function maketuple() takes variables and their names as arguments. tuple() is used to convert and store the 'n' number of variables in a tuple type. This method is used in complicated cases.

How do you convert a tuple element to a string in Python?

Use the str. join() Function to Convert Tuple to String in Python. The join() function, as its name suggests, is used to return a string that contains all the elements of sequence joined by an str separator. We use the join() function to add all the characters in the input tuple and then convert it to string.

How do you know if a variable is a tuple?

Method #1 : Using type() This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well.


2 Answers

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
like image 52
fredtantini Avatar answered Oct 16 '22 13:10

fredtantini


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

Remove them and you'll get it without a tuple

like image 21
thomas Avatar answered Oct 16 '22 15:10

thomas