Can python create a class that can be initialised with an instance of the same class object?
I've tried this:
class Class():
def __init__(self,**kwargs):
print self
self = kwargs.get('obj',self)
print self
if not hasattr(self,'attr1'):
print 'attr1'
self.attr1 = kwargs.pop('attr1',[])
if not hasattr(self,'attr2'):
print 'attr2'
self.attr2 = kwargs.pop('attr2',[])
print self
self.attr1 = kwargs.pop('attr1',self.attr1)
self.attr2 = kwargs.pop('attr2',self.attr2)
print self.attr1
print self.attr2
If I create a new instance there is no problem:
inst = Class(attr1=[1,2,3])
print inst
print inst.attr1,inst.attr2
The output is:
<__main__.Class instance at 0x7f2025834cf8>
<__main__.Class instance at 0x7f2025834cf8>
attr1
attr2
<__main__.Class instance at 0x7f2025834cf8>
[1, 2, 3]
[]
<__main__.Class instance at 0x7f2025834cf8>
[1, 2, 3] []
But if I create a new instance with the instance inst
:
inst2 = Class(obj=inst)
print inst2
print inst2.attr1,inst2.attr2
The output is:
<__main__.Class instance at 0x7f202584b7e8>
<__main__.Class instance at 0x7f2025835830>
<__main__.Class instance at 0x7f2025835830>
[1, 2, 3]
[]
<__main__.Class instance at 0x7f202584b7e8>
AttributeError Traceback (most recent call last)
<ipython-input-228-29c9869a9f4d> in <module>()
1 inst2 = Class(obj=inst)
2 print inst2
----> 3 print inst2.attr1,inst2.attr2
AttributeError: Class instance has no attribute 'attr1'
I handle the problem but i dont know how to solve it:
- in the 1st case the instance address is always the same ("inside" and "outside" the class)
in the 2nd case:
What is wrong ? How does address affectation work in Python?
Is it a good manner of doing this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…