typing question

Jason Swails jason.swails at gmail.com
Sat Aug 27 09:42:57 EDT 2011


Hello everyone,

This is probably a basic question with an obvious answer, but I don't quite
get why the type(foo).__name__ works differently for some class instances
and not for others.  If I have an "underived" class, any instance of that
class is simply of type "instance".  If I include an explicit base class,
then its type __name__ is the name of the class.

$ python
Python 2.7.2 (default, Aug 26 2011, 22:35:24)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
...     pass
...
>>> foo = MyClass()
>>> type(foo)
<type 'instance'>
>>> type(foo).__name__
'instance'
>>> class MyClass1():
...     pass
...
>>> bar = MyClass1()
>>> type(bar)
<type 'instance'>
>>> type(bar).__name__
'instance'
>>> class MyClass2(object):
...     pass
...
>>> foobar = MyClass2()
>>> type(foobar)
<class '__main__.MyClass2'>
>>> type(foobar).__name__
'MyClass2'

I can't explain this behavior (since doesn't every class inherit from object
by default? And if so, there should be no difference between any of my class
definitions).  I would prefer that every approach give me the name of the
class (rather than the first 2 just return 'instance').  Why is this not the
case?  Also, is there any way to access the name of the of the class type
foo or bar in the above example?

Thanks!
Jason

P.S.  I'll note that my "preferred" behavior is how python3.2 actually
operates

$ python3.2
Python 3.2.1 (default, Aug 26 2011, 23:20:19)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
...     pass
...
>>> foo = MyClass()
>>> type(foo).__name__
'MyClass'


-- 
Jason M. Swails
Quantum Theory Project,
University of Florida
Ph.D. Candidate
352-392-4032
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110827/0213265c/attachment.html>


More information about the Python-list mailing list