У меня есть следующий код для поиска экземпляров объектов в базе данных, а затем создания объектов Python с данными.
class Parent:
@staticmethod
def get(table, **kwargs):
"""retrieves a register in the DB given the kwargs"""
return get_from_db(table, **kwargs)
class ChildA(Parent):
_table = 'table_child_a'
def __init__(self, **kwargs):
"""adds the arguments retrieved in the DB"""
for k, v in attributes.items():
setattribute(self, k, v)
@classmethod
def get(cls, **kwargs):
"""retrieves the data from the db and creates a ChildA object with it"""
return ChildA(attributes=Parent.get(cls._table, **kwargs))
class ChildB(Parent):
_table = 'table_child_b'
def __init__(self, **kwargs):
"""adds the arguments retrieved in the DB"""
for k, v in attributes.items():
setattribute(self, k, v)
@classmethod
def get(cls, **kwargs):
"""retrieves the data from the db and creates a ChildB object with it"""
return ChildB(attributes=Parent.get(cls._table, **kwargs))
Можно ли реализовать метод получения детей в родительском элементе (поэтому мне не нужно реализовывать его каждый раз, когда я создаю дочерний класс), но чтобы знать, какие дочерние элементы возвращать (пожалуйста, имейте в виду, что это должно быть класс / статический метод.






Да, но вам придется переименовать один из них (не может быть двух методов с именем get). Глядя на это, нет никакой реальной причины иметь Parent.get, который просто обертывает get_from_db.
Идентичные методы __init__ также могут входить в Parent.
def get_from_db(table, **kwargs): # Just for illustration
print(table)
return {}
class Parent:
@classmethod
def get(cls, **kwargs):
"""retrieves the data from the db and creates a Parent subclass object with it"""
return cls(attributes=get_from_db(cls._table, **kwargs))
def __init__(self, **kwargs):
"""adds the arguments retrieved in the DB"""
for k, v in kwargs['attributes'].items():
setattr(self, k, v)
class ChildA(Parent):
_table = 'table_child_a'
class ChildB(Parent):
_table = 'table_child_b'
print(ChildA.get())
# table_child_a
# <__main__.ChildA object at 0x7ff9be8aa5f8>
Это сработало, это было намного проще, чем я думал, спасибо!
Учитывая, что метод класса получает аргумент класса, знать, какой дочерний элемент нужно вернуть, тривиально.