menu

arrow_back How do I properly create a parent class for multiple classes of daughters?

by
1 vote
Good afternoon. I have 3 daughter classes, each of which can call 3 of the same methods. In the class constructor there is a dictionary being filled in. But when I print out the dictionary, I find that each class contains data from all 3 classes. Can you tell me how to create classes correctly so that I don't have to write 3 identical methods in each one?
Example:
class CECommon:
data = {}

def get(self):
return self.data

def get_by_id(self, id, only_name=True):
if id not in self.data:
return False

return self.data[id]['name'] if only_name else self.data[id]

def search_by_name(self, name):
return {k: val for k, val in self.data.items() if val['name'].lower().count(name.lower())}


class AAA(CECommon):
def __init__(self, text):
for row in text.splitlines():
val = row.split(';')
self.data[int(val[0])] = {
'id': int(val[0]),
'pos_id': int(val[1]),
'name': val[2],
}

self.__data = dict(sorted(self.data.items(), key=lambda x: x[1]['name']))


class BBB(CECommon):
def __init__(self, text):
for row in text.splitlines():
val = row.split(';')
self.data[int(val[0])] = {
'id': int(val[0]),
'name': val[1],
}

self.__data = dict(sorted(self.data.items()))


class CCC(CECommon):
def __init__(self, text):
for row in text.splitlines():
val = row.split(';')
self.data[int(val[0])] = {
'id': int(val[0]),
'name': val[1],
}

self.__data = dict(sorted(self.data.items(), key=lambda x: x[1]['name']))
If you call CCC.get() (of course, after you have called all 3 classes before and filled them with data), you will get a dictionary with data from all (AAA, BBB, CCC) classes

1 Answer

by
 
Best answer
0 votes
Create a __init__ in CECommon and move the data initialization there. In descendants call super in init.