[Tutor] incomprehension in type of classes.

Cedric BRINER work at infomaniak.ch
Sat Apr 23 11:46:50 CEST 2005


> >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...
aaaaah... I din't know that there was two kinds of classes. So you mean that, now the new style object should be like: class A(object): pass

>>> class A: pass
...
>>> class B(object): pass
...
>>> a=A()
>>> b=B()

I see that dir (b) compare to dir(a) provides more stuff. So the new style of a class, is not only about syntax but also about properties ???

ok, I'll try to find more about this !

> 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__
this link is very usefull

thanks

Cedric BRINER


More information about the Tutor mailing list