Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12282 > unrolled thread

Re: typing question

Started byChris Rebert <clp2@rebertia.com>
First post2011-08-27 10:35 -0700
Last post2011-08-27 10:35 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: typing question Chris Rebert <clp2@rebertia.com> - 2011-08-27 10:35 -0700

#12282 — Re: typing question

FromChris Rebert <clp2@rebertia.com>
Date2011-08-27 10:35 -0700
SubjectRe: typing question
Message-ID<mailman.471.1314466517.27778.python-list@python.org>
On Sat, Aug 27, 2011 at 6:42 AM, Jason Swails <jason.swails@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web