Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #12282
| References | <CAEk9e3qF7LRnaFOU7bZSC5COnTr0v9Ch1B5pKT_9zTE1=12Y4w@mail.gmail.com> |
|---|---|
| Date | 2011-08-27 10:35 -0700 |
| Subject | Re: typing question |
| From | Chris Rebert <clp2@rebertia.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.471.1314466517.27778.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: typing question Chris Rebert <clp2@rebertia.com> - 2011-08-27 10:35 -0700
csiph-web