typing question

Chris Rebert clp2 at rebertia.com
Sat Aug 27 13:35:14 EDT 2011


On Sat, Aug 27, 2011 at 6:42 AM, Jason Swails <jason.swails at gmail.com> wrote:
> 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?

That's only true in Python 3.x.

Python 2.7.2 (default, Jul 27 2011, 04:14:23)
>>> class Foo:
...     pass
...
>>> Foo.__bases__
()
>>> class Bar(object):
...     pass
...
>>> Bar.__bases__
(<type 'object'>,)

> 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?

Classes directly or indirectly inheriting from `object` are
"new-style"; classes which don't are "old-style". The two kinds of
classes have different semantics (including whether they have a
.__name__, but that's minor relative to the other changes). Old-style
classes are deprecated and were removed in Python 3.
See http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes

Cheers,
Chris



More information about the Python-list mailing list