[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Trying to figure out the data type from the code snippet

On 30Jan2019 04:24, Chupo <bad_n_mad at> wrote:
>I am trying to figure out what data type is assigned to variable p in
>this code snippet:
>for p in game.players.passing():
>    print p,, p.passing_att, p.passer_rating()

Well, Python comes with a type() builtin function:

  print type(p)

>R.Wilson SEA 29 55.7
>J.Ryan SEA 1 158.3
>A.Rodgers GB 34 55.8
>If p is a string ('print p' prints names of the players) then how is
>possible to access p.something?

Well, if p is just a string, then you can't: strings don't have the 
attributes (".something") you're using. Thereofre p is not a string. (It 
_could_ be a subtype of str, but that is pretty unlikely.

What you're probably wanting to know is that the print statement calls 
str(x) for every "x" which it is asked to print, and that "p" has a 
__str__ method returning the "R.Wilson" string (etc). All object's have 
an __str__ method, and for "p" it has been defined to produce what looks 
like a player's name.

>If p is an object, then how can p return a string?

"p" is definitely an object: all values in Python are objects.

"p" doesn't return a string, it returns "p".

However, "print" actually prints "str(p)". So it is call's p's __str__ 
method to get a string to print out.

Think of it this way: print's purpose it to print things out, and it 
prints to the output which is text. You can only write strings to text, 
so print converts _everything_ it is given to a string. That "55.7" in 
your output: that is a string representing a floating point value.

Cameron Simpson <cs at>