我有以下代码来查找数据库中的对象实例,然后使用数据创建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))
是否可以在Parent中实现Children get方法(因此我不必在每次创建Child类时都实现它),但是要知道要返回什么类型的Children(请,请忍受)请注意,它必须是类/静态方法。
答案 0 :(得分:2)
是的,但您必须重命名其中一个(不能有两个名为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>