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

boB Stepp robertvstepp at gmail.com
Fri Feb 10 23:32:10 EST 2017


On Fri, Feb 10, 2017 at 8:05 PM, eryk sun <eryksun at gmail.com> wrote:

> Speaking of classes and metaclasses, note that you can't call
> int.__repr__(int) to get this representation, because the __repr__
> special method of int is meant for instances of int such as int(5).

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'

?

More experimentation.  Is this how I would define __repr__() for a custom class?

py3: class boB:
...     def __repr__(self):
...             return "<boB's namesake class>"
...
py3: x = boB()
py3: repr(x)
"<boB's namesake class>"

Seems to work.  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?

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?



-- 
boB


More information about the Tutor mailing list