Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python类返回空字典_Python_Oop - Fatal编程技术网

Python类返回空字典

Python类返回空字典,python,oop,Python,Oop,新手需要一些帮助使代码面向对象 我试图用不同的方法编写一个类来处理XML文件。其中一种方法的目标是返回一个字典,其中嵌入附件的文件名和编码的数据字符串分别作为键和值 我已经设法让它在课外发挥作用: 将xml.etree.ElementTree作为ET导入 tree=ET.parse('invoice.xml') root=tree.getroot() 名称空间={ 'cac':'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregat

新手需要一些帮助使代码面向对象

我试图用不同的方法编写一个类来处理XML文件。其中一种方法的目标是返回一个字典,其中嵌入附件的文件名和编码的数据字符串分别作为键和值

我已经设法让它在课外发挥作用:

将xml.etree.ElementTree作为ET导入
tree=ET.parse('invoice.xml')
root=tree.getroot()
名称空间={
'cac':'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',
“cbc”:“urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2”,
'ext':'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2',
“ccts”:“urn:un:unece:uncefact:documentation:2”,
'xsi':'http://www.w3.org/2001/XMLSchema-instance'
}
附件={}
对于root.findall('cac:AdditionalDocumentReference',命名空间)中的文档:
filename=document.find('cbc:ID',名称空间)。text
打印(文件名)
#查找嵌入的文件
对于document.findall('cac:Attachment',命名空间)中的子级:
附件=child.find('cbc:EmbeddedDocumentBinaryObject',命名空间)。文本
附件[文件名]=附件
但我无法将其转换为类方法,因为类方法返回一个空字典。我正在编写的代码:

将xml.etree.ElementTree作为ET导入
类别发票:
"""
与EHF发票相关的常见任务。
"""
名称空间={
'cac':'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',
“cbc”:“urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2”,
'ext':'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2',
“ccts”:“urn:un:unece:uncefact:documentation:2”,
'xsi':'http://www.w3.org/2001/XMLSchema-instance'
}
附件={}
定义初始(自我,发票):
“”“初始化发票属性。”“”
self.invoice=发票
#EHF发票中使用的命名空间字典
self.namespace=self.namespace
def编码的_附件(自身):
"""
以编码形式返回EHF发票中的嵌入附件
作为一本字典。
Keys=文件名
Value=base64编码文件
"""
对于self.invoice.findall('cac:AdditonalDocumentReference',self.namespace'中的文档:
#查找文件名
filename=document.find('cbc:ID',self.namespace.).text
#查找嵌入的文件
对于document.findall('cac:Attachment',命名空间)中的子级:
附件=child.find('cbc:EmbeddedDocumentBinaryObject',self.namespace.).text
#将文件名和附件添加到字典
self.attachments[filename]=附件
返回(self.attachments)
tree=ET.parse('invoice.xml')
root=tree.getroot()
ehf=发票(根)
attach_dict=ehf.encoded_attachments()
打印(附目录)
我认为我在课堂上遗漏了一些重要的东西。感谢您的帮助

编辑:

xml文件的一部分。用伪文本字符串替换编码数据


urn:cen.eu:en16931:2017 35;合规#urn:fdc:peppol。eu:2017:poacc:billing:3.0
urn:fdc:peppol.eu:2017:poacc:billing:01:1.0
1060649
2020-01-23
2020-02-07
380
2020-01-23
诺克
不适用
发票\附件\文件名.pdf
130
商业发票
BASE64ENCODEDTEXT

self的用法不一致

for child in document.findall('cac:Attachment', **namespace**):
    attachment = child.find('cbc:EmbeddedDocumentBinaryObject', **self.namespace**).text

self
的用法不一致

for child in document.findall('cac:Attachment', **namespace**):
    attachment = child.find('cbc:EmbeddedDocumentBinaryObject', **self.namespace**).text

您在这里犯了两个错误。
一个是您正在使用类变量(请阅读此处:)
第二个是gokaai说的

这应该起作用:

import xml.etree.ElementTree as ET


class Invoice:
    """
    Common tasks in relation to EHF invoices.
    """

    def __init__(self, invoice):
        """Initialize invoice attributes."""
        self.invoice = invoice
        self.namespace = {
            'cac': 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-3',
            'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-3',
            'ext': 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-3',
            'ccts': 'urn:un:unece:uncefact:documentation:1',
            'xsi': 'http://www.w2.org/2001/XMLSchema-instance'
        }
        self.attachments = {}

    def encoded_attachments(self):
        """
        Return the embedded attachments from the EHF invoice in encoded form
        as a dictionary.

        Keys = filenames
        Value = base64 encoded files
        """

        for document in self.invoice.findall('cac:AdditonalDocumentReference', self.namespace):
            # Find filename
            filename = document.find('cbc:ID', self.namespace).text

            # Find the embedded file
            for child in document.findall('cac:Attachment', self.namespace):
                # Add filename and attachment to dictionary
                self.attachments[filename] = child.find('cbc:EmbeddedDocumentBinaryObject', self.namespace).text

        return self.attachments

您在这里犯了两个错误。
一个是您正在使用类变量(请阅读此处:)
第二个是gokaai说的

这应该起作用:

import xml.etree.ElementTree as ET


class Invoice:
    """
    Common tasks in relation to EHF invoices.
    """

    def __init__(self, invoice):
        """Initialize invoice attributes."""
        self.invoice = invoice
        self.namespace = {
            'cac': 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-3',
            'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-3',
            'ext': 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-3',
            'ccts': 'urn:un:unece:uncefact:documentation:1',
            'xsi': 'http://www.w2.org/2001/XMLSchema-instance'
        }
        self.attachments = {}

    def encoded_attachments(self):
        """
        Return the embedded attachments from the EHF invoice in encoded form
        as a dictionary.

        Keys = filenames
        Value = base64 encoded files
        """

        for document in self.invoice.findall('cac:AdditonalDocumentReference', self.namespace):
            # Find filename
            filename = document.find('cbc:ID', self.namespace).text

            # Find the embedded file
            for child in document.findall('cac:Attachment', self.namespace):
                # Add filename and attachment to dictionary
                self.attachments[filename] = child.find('cbc:EmbeddedDocumentBinaryObject', self.namespace).text

        return self.attachments
答案是(鼓声…)一切都是正确的,但在这里比较新旧代码:

old: for document in root.findall('cac:AdditionalDocumentReference', namespace)
new: for document in self.invoice.findall('cac:AdditonalDocumentReference', self.namespace)
                                                    ^
顺便说一下,您可以省去行
self.namespace=self.namespace

,答案是(鼓点…)一切都是正确的,但在这里比较新旧代码:

old: for document in root.findall('cac:AdditionalDocumentReference', namespace)
new: for document in self.invoice.findall('cac:AdditonalDocumentReference', self.namespace)
                                                    ^

顺便说一下,您可以省去行
self.namespace=self.namespace

欢迎使用堆栈溢出。很清楚您想要实现什么,但是您是否也可以发布您试图解析的xml文件的一部分,以便人们可以像您这样运行和调试代码?@Ronald添加了与问题相关的部分xml。欢迎来到Stack Overflow。很清楚您想要实现什么,但是您是否也可以发布您试图解析的xml文件的一部分,以便人们可以像您这样运行和调试代码?@Ronald添加了与问题相关的xml部分。谢谢。编辑了代码,但没有解决我的问题。谢谢。编辑了代码,虽然它没有解决我遇到的问题。应该有效还是将有效?我不明白为什么使用类变量是一个错误?我无法测试它,因为我没有输入XML。如果在这里使用类变量并使用该类的多个不同对象,它们将覆盖其他变量。这就是为什么在这种情况下使用类变量是错误的。如果您想使用它们,您需要确保在任何时间点只有该类的一个对象,从而使该类本身过时。类变量可用于其所有成员。名称空间变量通常适合用作类变量,因为它既没有更改,也没有特定于成员。好的,您可以将
名称空间
设置为类变量,但他在任何地方使用的
自我名称空间
都是错误的。我不知道他的每一个例子