如何在父类@classmethod

时间:2018-03-27 01:30:49

标签: python python-3.x oop inheritance

我有以下代码来查找数据库中的对象实例,然后使用数据创建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(请,请忍受)请注意,它必须是类/静态方法。

1 个答案:

答案 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>