[Tutor] odd behavior within __init__
Rich Krauter
rmkrauter at yahoo.com
Thu Apr 14 13:33:02 CEST 2005
Orri Ganel wrote:
> Hello all,
>
> As part of a project i'm doing (mostly for the fun of it), I have a
> class which creates a sort of wrapper around any object to make it
> suitable for use in a custom container. However, if the class
> receives an already wrapped object, I want it to just return the
> object (same id and everything as the original). Now, the following
> seems to work in the __init__ method (due to output), but then it
> disappears as soon as the __init__ method is left:
>
> class Node:
> ...
> def __init__(self, cargo=None, prev=None, next=None, nod=False):
> """x.__init__(...) initializes x; see
> x.__class__.__doc__ for signature"""
> if not isinstance(cargo, Node) or nod:
> self.cargo = cargo
> self.prev = prev
> self.next = next
> else:
> self = cargo
> print id(self), id(cargo)
> print self.cargo
>
>
>>>>a = Node(1)
>>>>b = Node(a)
>
> 12932600 12932600
> 1
>
>>>>id(b)
>
> 12960632
>
> Any ideas on why this happens, or suggestions as to how to implement
> the behavior I'm looking for (in which b and a would refer to the same
> object, have the same id, etc.), would be greatly appreciated.
>
> Thanks in advance,
> Orri
>
Orri,
Maybe you could use a factory. It would allow you to simplify your Node
class, and encapsulate the instantiation behavior you want outside the
class.
class Node(object):
def __init__(self,cargo=None,prev=None,next=None):
self.cargo = cargo
self.prev = prev
self.next = next
def factory(cargo=None,prev=None,next=None):
if isinstance(cargo,Node):
return cargo
else:
return Node(cargo,prev,next)
n1 = factory(1)
print id(n1)
n2 = factory(n1)
print id(n2)
Good luck,
Rich
More information about the Tutor
mailing list