I am using python 2.7 and I want to create some kind of data structure, using classes
Question A:
Let's say that I create this class:
class my_data():
def __init__(self,data1,data2,data3):
self.data1 = data1
self.data2 = data2
self.data3 = data3
and after that I create some instances of the class, e.g.
d1 = my_data(1,2,None)
d2 = my_data(4,5,d1)
d3 = my_data(7,8,d2)
As you see, data3 may be None or an instance. So far so good.
Now, let's once more try to create some other instances (the hard way):
d2 = my_data(4,5,d1)
d1 = my_data(1,2,None)
d3 = my_data(7,8,d2)
In this case NameError Exception will occur, because obviously in line d2 = my_data(4,5,d1), d1 has not been defined.
So, here is the question: I want to create instances in which data3 should be None or an instance. If data3 is None or an existed instance, no problem. But if data3 refers to an unexisted instance, I want that instance to be created.
For example: d2 = my_data(4,5,d1)
if d1 does not exist, I want to be initiated as a dummy instance d1 = my_data(None,None,None), and after that, d2 to be initiated as well
I tried this but doesn't seem to do the trick:
class my_data():
def __init__(self,data1,data2,data3):
self.data1 = data1
self.data2 = data2
try:
self.data3 = data3
except:
data3 = my_data(None,None,None)
self.data3 = data3
Question B:
Let's say that somehow we have created some instances (d1,d2,d3,...) of the class. How can I store the instances in a list inside the class, so every instance which has been created in this class to be included in the list?
something like my_data.my_list() which will produce [d1, d2, d3, ...]
Any ideas will be appreciated
my_dataconstructor is not passed the named1. It is passed the object that the variabled1refers to. Ifd1does not refer to anything, theNameErroroccurs before the constructor can do anything about it.