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



你好,我有以下情况:

  • 从双亲类继承的专用类
  • 需要在运行时定义最专业的类,这是基于我只有在开始从数据库读取数据时才能获得的一些信息

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

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__((,但我认为该类型只会创建一个新类型,而不会立即实例化一个。所以我的问题是,现在是否有办法推迟实例的实例化。

提前感谢您在这方面的任何帮助和提示。

--MD。

初始化发生在第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