Answer the question
In order to leave comments, you need to log in
How to properly create a parent class for multiple child classes?
Good afternoon. I have 3 child classes, each of which can call 3 identical methods. In the class constructor, the dictionary is being filled. But when I print out the dictionary, I find that each class contains data from all 3 classes. Tell me how to create classes correctly so that you don’t have to write 3 identical methods in each?
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']))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question