ok i have a class and in it's constructor i want to create a copy of
it as an attribute, i have tried super, __new__, and noting seems to
work, please help!
class A(base):
def __init__(self):
super(A, self).__init__()
self.nested = ?
think of a nested list [ [] ] but with object "A" as the toplevel list
and having an instance of A in the attribute "nested"
Well, to answer the question you asked ("i have a class and in it's
constructor i want to create a copy of it as an attribute"):
self.nested = copy.copy(self)
However, your post contains some conflicting information, "copy" often
means different things to different people, "it" is ambiguous, and
what you ask for seems to to be well-conceived. I think we will be
able to help you more if you give more details about what you expect
and how you intend to use this nested object.
Please try to observe the distiction between classes and instances
(you almost certainly wanted a copy of the instance, not of the
class).
ok here is some code. this will cause an infinite recursion.
class A():
def __init__(self, *args):
self.nestedA = A(*args) #NO GOOD!
there must be a way to create an instance of an object within the same
objects constructor?
Here's something to ponder:
If you have two objects, one of which has an attribute that contains
certain nested object, one which doesn't, should those objects be
instances of the same class?
You may come to a different conclusion, but it seems to me they ought
to be different classes. They have a significant difference in their
behavior.
class Inner(base):
def __init__(self,*args):
super(self,Inner).__init__(*args)
class Outer(Inner):
def __init__(self,*args):
super(self,Outer).__init__(*args)
self.nested = Inner(*args)
If you insist on them being the same class, you could use copy.copy()
as I did earlier, although it won't always work for every class. Or
just pass a parameter to the class indicating whether it should create
a nested copy of itself, defaulting to True. When creating the nested
class it should be set to False. (Note: because keyword-only
arguments aren't in Python 2.5 I capture _create_nested in kwargs.
You may find it more convenient to use a keyword argument.)
class A(base):
def __init__(self,*args,**kwargs):
_create_nested = kwargs.pop('_create_nested',True)
super(A,self).__init__(*args,**kwargs)
if _create_nested:
self.nested = A(_create_nested=False,*args)
Carl Banks