[Tutor] incomprehension in type of classes.

Kent Johnson kent37 at tds.net
Fri Apr 22 14:07:18 CEST 2005


Cedric BRINER wrote:
> in my python code I have changed some classes like the following
> 
> from (I):
> 
> class CYear:
>    def __init__(self, year):
>       self.__year=year
>       print str(self.__year)             <<---(*)
>       print 'dir of: '+str(dir(self))
>       print 'type of: '+str(type(self))
>    def __str__(self):
>       return "we are in "+str(self.year)
> 
> 
> to (IIOB):
> 
> class CYearDerived(int):
>    def __init__(self, year):
>       super(CYearDerived,self).__init__(year)
>       self.__year=year
>       print str(self.__year)            <<-----(*OB)
>       print 'dir of: '+str( dir(self) )
>       print 'type of: '+str(type(self))
>    def __str__(self):
>       return "we are in "+super(CYearDerived,self).__str__()

> why type of (CYear(2005))
> <type 'instance'>
> 
> and type(CYearDerived)
> <class '__main__.CYearDerived'>
> 
> doesn't give the same type ???

It's a difference between new-style and old-style classes. CYear is an old-style class because it 
doesn't inherit from object. CYearDerived is a new-style class because it inherits from int which is 
a subtype of object:

  >>> class C: pass # old-style class
  ...
  >>> type(C())
<type 'instance'>
  >>> C().__class__
<class __main__.C at 0x008CE7B0>

  >>> class C2(object): pass # new-style class
  ...
  >>> type(C2())
<class '__main__.C2'>
  >>> C2().__class__
<class '__main__.C2'>

  >>> int.__bases__ # int inherits from object
(<type 'object'>,)

I'm not sure *why* there is this difference between the two types of classes, but there is...

By the way extending int does not work the way you have done it here. int is an immutable type so 
you have to initialize it in the __new__() method, not in __init__(). Read the details here:
http://www.python.org/2.2/descrintro.html#__new__

Kent



More information about the Tutor mailing list