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
, and c
) or initial fields (of
foo
) unchanged;
- keep track of these and use them (i.e., my final object should be able to use "inside itself" the initial
OneNumber
and MainObject
instances to use their fields and produce new things, here through the self.getNewNumber
method);
- be able to call the relevant resulting combinations individually (i.e., here "1st" for the [
a
vsfoo
] combination, "2nd" for [b
vsfoo
], 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}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…