gpt4 book ai didi

python - 如何在父@classmethod 中引用子类

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:46 25 4
gpt4 key购买 nike

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

最佳答案

是的,但是您必须重命名其中之一(不能有两个方法都命名为 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>

关于python - 如何在父@classmethod 中引用子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49503062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com