将参数传递给类实例

时间:2020-02-20 14:11:33

标签: python owlready

我有1个在运行时定义的类,该类从基于以下类型定义的类继承:MasterData或Transaction,而该类又从BusinessDocument继承。 -BusinessDocument类需要从可通过外部模块访问的[Thing] [2]类继承。

已实施以下代码来创建链中的所有类:

from owlready2 import *

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

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

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

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

with onto:
    class MasterData(BusinessDocument):
        def __init__(self, doc_id, location, color, size):
            BusinessDocument.__init__(self, doc_id, location, color, size, 'MasterData')

with onto:    
    class Transactional(BusinessDocument):
        def __init__(self, doc_id, location, color, size):
            BusinessDocument.__init__(self, doc_id, location, color, size, 'Transactional')


with onto:
    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', 'color', 'size',])) 

在运行时,我通过调用以下内容来获得新的课程:

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

尝试调用InvoiceClass('INV01','New York','Blue','Large')实例化该类后,经历了两天的错误,我发现Thing类只会创建一个实例,如果我使用以下格式拨打电话:

InvoiceClass(doc_id = 'INV01', location = 'New York', color = 'Blue', size = 'Large')

我正在寻找有关如何通过常规方法处理实例化的建议。我考虑过可能要实现一个 init 方法,以将属性以期望的格式传递给Thing,但是我不确定该怎么做。

先谢谢了。

-MD

0 个答案:

没有答案