[Tutor] Test for type(object) == ???

eryk sun eryksun at gmail.com
Sat Feb 11 00:27:54 EST 2017


On Sat, Feb 11, 2017 at 4:32 AM, boB Stepp <robertvstepp at gmail.com> wrote:
>
> This bit got me experimenting.  Since the integer "5" is an integer
> object instance, I am wondering why I can't do:
>
> py3: 5.__repr__()
>   File "<stdin>", line 1
>     5.__repr__()
>              ^
> SyntaxError: invalid syntax
>
> , but I can do:
>
> py3: x = 5
> py3: x.__repr__()
> '5'

The parser sees "5." as a floating point number. You can use
parentheses to force it to parse 5 as an integer:

    >>> (5).__repr__()
    '5'

> But in class examples I've seen posted, I do not recall __repr__ ever
> being defined.  So I infer that most of the time I should not or need not
> do so, but under what circumstances should I do so?

Classes inherit a default __repr__ from `object`. For example:

    >>> object.__repr__(5)
    '<int object at 0xa68ac0>'

Define a custom __repr__ when it's useful for debugging to include
additional information. It also gets called for str() if you don't
implement a custom __str__.

> Another curiosity question.  If I type:
>
> py3: repr(int)
> "<class 'int'>"
>
> I get what I expect, but if I do the same with my custom class, "boB",
> I instead get:
>
> py3: repr(boB)
> "<class '__main__.boB'>"
>
> Why the difference between the Python class "int" and my custom class
> "boB"?  Did I not define __repr__() correctly?

The __repr__ defined by your class is used for instances of the class,
not for the class itself. In the above you're seeing the return value
from the metaclass __repr__ that's defined by `type`:

In CPython, type.__repr__ is implemented in C as type_repr in
Objects/typeobject.c. If it can determine the module and qualified
name of a class, then it uses the template "<class '%U.%U'>".
Otherwise it uses the template "<class '%s'>" with the basic char
*tp_name from the PyTypeObject.


More information about the Tutor mailing list