[Tutor] basic class loading question

Karim Meiborg karim.meiborg at googlemail.com
Tue Nov 22 18:13:02 CET 2011

Cranky Frankie wrote:

> OK, but this is still not working:
> class Qb:
>     def __init__(self, first_name='', last_name='', phone='',
> email='', stadium=''):
>         self.first_name = first_name
>         self.last_name = last_name
>         self.phone = phone
>         self.email = email
>         self.stadium = stadium
> Qb_list = [["Joe", "Montana", "415-123-4567",
> "joe.montana at gmail.com","Candlestick Park"],
>     ["Fran", "Tarkington","651-321-7657",
> "frank.tarkington at gmail.com", "Metropolitan Stadidum"],
>     ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea
>     [Stadium"], "John", "Elway", "303-9876-333", "john.elway at gmai.com",
>     ["Mile
> High Stadium"],
>     ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com",
> "Louisiana Superdome"],
>     ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com",
> "Cowboy Stadium"]]
> len_Qb_list = len(Qb_list)
> for i in range(0, len_Qb_list):
>     quarterbacks = Qb(*Qb_list[i])
>     i = i + 1 
> print(quarterbacks.last_name(2))

this is my first post in this group so hopefully I don't mess up. 

I think your real problem here is the for-loop and not the class 
instantiation itself. Below is the minimally modified working version of 
your code:

    len_Qb_list = len(Qb_list)
    for i in range(0, len_Qb_list):
        quarterbacks = Qb(*Qb_list[i])

Have a look at the differences:
  - The for-loop itself increments i, you don't have to do it yourself
  - The printed expression is different:
    quarterbacks.last_name(2) implies a function call, whereas 
    quarterbacks.last_name refers to an attribute
  - The indentation was modified by me to print every last name.
    With your indentation only the last last name would be printed.
    Since I'm not sure what you want to accomplish this may be wrong for

Here is a somewhat nicer version, which does exactly the same:

    quarterbacks = [Qb(*quarterback) for quarterback in Qb_list]
    for quarterback in quarterbacks:

It is easier to read (at least in my opinion) and less typing too.
If you'd like to understand the syntax, i'd recommend you to look up
"list comprehension" in your book of choice.

This would be the minimal version of code to print out all the last names(at 
least at my level of understanding):

[print(Qb(*quarterback).last_name) for quarterback in Qb_list]

I hope this helps. I'm new to python, so please take my advice with a grain 
of salt.


More information about the Tutor mailing list