Initializing a class print question


#1



https://www.codecademy.com/courses/python-intermediate-en-egNXj/0/5?curriculum_id=4f89dab3d788890003000096#

Do we have to call to print each item individually like in the code below? Is there no other way to do with less code? I am thinking this would become somewhat tiresome as the arguments in each method increase.


print (my_car.model)
print (my_car.color)
print (my_car.mpg)


#2

It will depend on what member you wish to query. If all, then iterate the object...

for key in my_car:
    print ("%s: %r" % (key, my_car[key]))

What you have is the correct way to print a single member.

Note: The parens are not needed in Python 2 (this lesson) but are needed in Python 3 as you will soon discover. It is still accepted in Python 2 so practice writing the parens around print arguments so you have this habit once you embark on Python 3.

Just to clarify, in the format arguments, a list must be in parens for either language.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.