gpt4 book ai didi

python - 关于多重继承、动态类创建和实例化的问题

转载 作者:行者123 更新时间:2023-12-01 06:22:53 25 4
gpt4 key购买 nike

您好,我有以下情况:

  • 从两个父类继承的专用类
  • 需要在运行时根据我开始从数据库读取数据时获得的一些信息来定义最专业的类。

我定义了以下代码来处理链中所有类的创建:

class BusinessDocument():
@staticmethod
def get_class(doc_type):
switch = {
'MasterData': MasterData,
'Transactional': Transactional
}
func = switch.get(doc_type, lambda: "Invalid Noun Type")
return func()

def __init__(self, doc_id, location, doc_type):
self.doc_id = doc_id
self.location = location
self.doc_type = doc_type
pass

@property
def get_location(self):
return self.location

@property
def get_doc_id(self):
return self.doc_id

class MasterData(BusinessDocument):
def __init__(self, doc_id, location):
BusinessDocument.__init__(self, doc_id, location, 'MasterData')

class Transactional(BusinessDocument):
def __init__(self, doc_id, location):
BusinessDocument.__init__(self, doc_id, location, 'Transactional')


class NounClass():
@staticmethod
def get_class(doc_name, doc_type):
return type(doc_name, (BusinessDocument.get_class(doc_type),
BusinessDocument, ),dict.fromkeys(['doc_id', 'location']))

然后在运行时,当我获取 doc_name 时,我尝试创建一个新类。此时,我可能没有所需的参数 doc_idlocation,但我需要类类型。

invoice_cls = NounClass.get_class('Invoice', 'Transactional')

我收到以下错误:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-cb774746875a> in <module>
----> 1 invoice_cls = NounClass.get_class('Invoice', 'Transactional')

<ipython-input-9-aa5e0b316ed1> in get_class(doc_name, doc_type)
35 @staticmethod
36 def get_class(doc_name, doc_type):
---> 37 return type(doc_name, (BusinessDocument.get_class(doc_type),
38 BusinessDocument, ),dict.fromkeys(['doc_id', 'location']))

<ipython-input-9-aa5e0b316ed1> in get_class(doc_type)
7 }
8 func = switch.get(doc_type, lambda: "Invalid Noun Type")
----> 9 return func()
10
11 def __init__(self, doc_id, location, doc_type):

TypeError: __init__() missing 2 required positional arguments: 'doc_id' and 'location'

我理解其原因是因为 __init__() 将在类实例化期间被调用,但我认为该类型只会创建一种新类型,而不会立即实例化一个类型。所以我的问题是是否有办法推迟此时实例的实例化。

预先感谢您对此提供的任何帮助和提示。

--医学博士。

最佳答案

初始化发生在第 9 行:

    return func()

我假设您想返回一个类对象,因此删除这些括号。

此外,func 也具有误导性,我已将其更改为 cls:

def get_class(doc_type):
switch = {
'MasterData': MasterData,
'Transactional': Transactional
}
cls = switch.get(doc_type, lambda: "Invalid Noun Type")
return cls

关于python - 关于多重继承、动态类创建和实例化的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60281424/

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