首页 > 解决方案 > 在 Python 的面向对象编程中 self 如何工作?

问题描述

我正在从 XSD 模式文件的子集生成示例 XML。我已经使用 GenerateDS 生成了数据对象。我实例化了父对象,并使用带有反射的递归来填充所有子对象,这样我就可以写出这个父对象及其所有子对象的 XML。稍后,我想用测试数据填充所有数据属性以创建我的测试 XML。

我的 XSD 生成的代码 GenerateDS 有问题。我不确定这是否是我对 Python 中的面向对象编程缺乏了解,或者它是否是库的问题,也许有人可以帮助我。这就是问题所在。当我运行导出方法时,它执行 self.exportChildren(outfile, level + 1, '', namespacedef_, name_='requestHeaderType', pretty_print=pretty_print) 并将文件对象传递到 outfile 并且 level 是 at0 + 1但问题是当 exportChildren 执行时,这里是参数, self.Header.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Header', pretty_print=pretty_print) 标头导出方法中的参数 outfile 采用 level 的值。

标头导出的方法签名是export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='Header', pretty_print=True):

我之前在 Python 中创建了类,当我调用类方法时,self 参数将被跳过,我传递给方法调用的第一个参数将是 self 参数之后的下一个参数。但是,在这种情况下,方法调用会用 outfile 覆盖 self ,并且我的 Header 对象变成了 File 对象。这很奇怪,我不明白为什么会发生这种情况。

我一直在我的 Visual Studio Code 调试器中使用 Python 3.6 在 Anaconda 上运行它。

这是我创建的代码。

import po3

def get_class( kls ):
    parts = kls.split('.')
    module = ".".join(parts[:-1])
    m = __import__( module )
    for comp in parts[1:]:
        m = getattr(m, comp)            
    return m

def recursiveInstantiation(obj):
    for key in vars(obj).keys():
        if '_' not in key and \
            'subclass' not in key and \
            'superclass' not in key and \
            'factory' not in key and \
            'export' not in key and \
            'build' not in key:
            subClass = recursiveInstantiation(get_class('po3.' + key))
            getattr(obj, 'set_' + key)(subClass)
    return obj

er = recursiveInstantiation(po3.EstablishRequest())

print(er.get_requestHeaderType()) # returns requestHeaderType object
print(er.get_requestHeaderType().get_Header()) # returns an exception posted below
#with open('file.xml', 'w') as outfile:
#    er.export(outfile, 0) # calling this produces the behavior I described above

这是我运行此脚本时的输出:

<class 'po3.requestHeaderType'>
Traceback (most recent call last):
  File "c:\Users\arychlik\Desktop\New folder (3)\generateXml.py", line 26, in <module>
    print(er.get_requestHeaderType().get_Header())
TypeError: get_Header() missing 1 required positional argument: 'self'

我希望方法调用跳过 self 参数,但它实际上是为 self 赋值,它用 File 对象覆盖它。

标签: pythonxmloopxsdpython-generateds

解决方案


推荐阅读