Given instances from two different Classes in Python, I would like to combine them to produce either a new object which has "memory" of the combined objects or a modified instance that conserves its initial properties but develops new ones (as done here).
Obviously, the example below is stupid, but is made for explanatory purposes.
So I have the object foo (class MainObject) which should be combined with different instances of the class OneNumber (here, a, b and c). I need to:
- keep the original objects (
a,b, andc) or initial fields (offoo) unchanged; - keep track of these and use them (i.e., my final object should be able to use "inside itself" the initial
OneNumberandMainObjectinstances to use their fields and produce new things, here through theself.getNewNumbermethod); - be able to call the relevant resulting combinations individually (i.e., here "1st" for the [
avsfoo] combination, "2nd" for [bvsfoo], etc.).
To address the 3 above, I create a dictionary to store individual combinations. Then, how to ideally create the keys? Obviously, it is suboptimal here. Giving a self.name field to the OneNumber class could be a better (?) option.
But I am sure real programmers must have a better way to do this all, right?
Would for example creating a new "combination" Class (with one instance of OneNumber and the instance of MainObject passed as arguments - three times to create three new objects, then) be better?
class OneNumber():
def __init__(self, n):
self.number = n
class MainObject():
def __init__(self, n):
self.number = n
self.dic = {}
self.newnumber = {}
self.keys = ['3rd', '2dn', '1st']
def combineOneNumber(self, onenum):
combname = self.keys.pop()
self.dic[combname] = onenum
self.getNewNumber(combname)
def getNewNumber(self, combname):
self.newnumber[combname] = self.number + self.dic[combname].number
a = OneNumber(8)
b = OneNumber(13)
c = OneNumber(23)
foo = MainObject(2)
foo.combineOneNumber(a)
foo.combineOneNumber(b)
foo.combineOneNumber(c)
print(foo.newnumber)
# {'1st': 10, '2dn': 15, '3rd': 25}