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

2024-10-04 11:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我有以下情况:

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

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

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_名称并尝试创建一个新类时。此时,我可能没有所需的参数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'

我理解这样做的原因是因为在类实例化期间将调用_uinit__;(),但我认为该类型只会创建一个新类型,而不会立即实例化一个。所以我的问题是,现在是否有办法推迟实例的实例化

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

--医学博士


Tags: nameselfidgetdocreturninitdef
1条回答
网友
1楼 · 发布于 2024-10-04 11:35:06

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

相关问题 更多 >