Mystery Theater New Style Classes

Gary Herron gherron at islandtraining.com
Thu Jul 24 15:02:45 EDT 2003


On Thursday 24 July 2003 09:05 am, Bob Gailer wrote:
> Predict the output:
>
> class A(int):
>      classval = 99
>      def __init__(self, val = 0):
>          if val:
>              self = val
>          else:
>              self = A.classval
> a=A(3)
> b=A()
> print a,b
>
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625

Since A this is a subclass of int, an immutable type, the asignment to
'self' is a red herring -- it has no affect.  That's clearer here:

>>> class A(int):
...   def __init__(self, val):
...     print 'Initial value of self:', self
...     self = 'Huh?'
...     print 'Final value of self:', self
...
>>> a = A(123)
Initial value of self: 123
Final value of self: Huh?
>>> print a
123

For immutable types, you need to create the object with the proper
value a little earlier in the creation process, and that's where the
method __new__ comes in.  This works as expected:

>>> class A(int):
...      classval = 99
...      def __new__(cls, val = 0):
...          if val:
...              return int.__new__(cls, val)
...          else:
...              return int.__new__(cls, A.classval)
...
>>> a=A(3)
>>> b=A()
>>> print a,b
3 99
>>>


See

  http://www.python.org/2.2/descrintro.html#__new__ 

for more details.

Gary Herron







More information about the Python-list mailing list