Python 如何使类从lxml.objectify.Element继承?

Python 如何使类从lxml.objectify.Element继承?,python,inheritance,lxml,lxml.objectify,Python,Inheritance,Lxml,Lxml.objectify,我有一个Python类,用于继承的Person对象 我计划扩展我的Person类,以包括其他属性和子标签。在执行此操作之前,我希望通过将类转换为使用来简化属性访问 不幸的是,尝试从objectify.Element继承会在创建cython\u函数\u或\u方法实例时引发类型错误 Traceback (most recent call last): File "C:/Users/svascellar/.PyCharmCE2017.3/config/scratches/scratch_1.py"

我有一个Python类,用于继承的
Person
对象

我计划扩展我的
Person
类,以包括其他属性和子标签。在执行此操作之前,我希望通过将类转换为使用来简化属性访问

不幸的是,尝试从
objectify.Element
继承会在创建
cython\u函数\u或\u方法
实例时引发类型错误

Traceback (most recent call last):
  File "C:/Users/svascellar/.PyCharmCE2017.3/config/scratches/scratch_1.py", line 2, in <module>
    class Person(objectify.Element):
TypeError: cannot create 'cython_function_or_method' instances
回溯(最近一次呼叫最后一次):
文件“C:/Users/svascellar/.PyCharmCE2017.3/config/scratch/scratch_1.py”,第2行,在
类人员(objectify.Element):
TypeError:无法创建“cython函数”或“方法”实例
为什么我的班级会出现打字错误?如何继承from
lxml.objectify.Element

事后看来,我建议不要使用
lxml
创建子类。 正如评论所提到的,这不是一门课。它是一个创建并返回对象的函数,这意味着它不能被继承

虽然可以从或继承,但lxml文档强烈警告您不能覆盖我最初的回答所做的
\uuuuu init\uuuuu
\uuuu new\uuuuuu

大肥肉警告:子类不能覆盖
\uuuuu init\uuuuuuu
\uuuuu new\uuuuuuuu
,因为在创建或销毁这些对象时,它是绝对未定义的。元素的所有持久状态都必须存储在底层XML中。如果创建后确实需要初始化对象,可以实现一个_init(self)方法,该方法将在对象创建后直接调用。
-

我建议改为从其他类继承。正如在原始问题中提到的,您可以相当容易地继承

from xml.etree import ElementTree
class Person(ElementTree.Element):
    def __init__(self, name, age):
        super().__init__("person", name=name, age=str(age))

person = Person("Paul", 23)
使用
lxml
的子类可能会带来更多的麻烦。但是,如果您真的想不顾警告而将
lxml
子类化,您可以在下面看到我的原始答案


旧答案(不安全) 尝试从
lxml.objectify.ObjectifiedElement继承

from lxml import objectify
class person(objectify.ObjectifiedElement):
    def __init__(self, name, age):
        super().__init__(name=name, age=str(age))

my_person = person("Paul", 23)
print(etree.tostring(my_person, encoding="unicode"))
# output: <person age="23" name="Paul"/>

将我的类更改为继承自
lxml.objectify.ObjectifiedElement
后,该类按预期工作。

您没有这样做,因为
lxml.objectify.Element
不是一个类型。正如错误所述:
objectify.Element
不是一个类,而是一个
cyfunction
(一个用Cython编码的函数),因此,您不能从它继承。相关:在下面引用lxml文档中的大肥肉警告的地方,您写了“正如原始问题中提到的,您可以非常容易地从
lxml.etree.ElementTree.Element
继承。”-应该是
xml.
而不是
lxml.
from xml.etree import ElementTree
class Person(ElementTree.Element):
    def __init__(self, name, age):
        super().__init__("person", name=name, age=str(age))

person = Person("Paul", 23)
from lxml import objectify
class person(objectify.ObjectifiedElement):
    def __init__(self, name, age):
        super().__init__(name=name, age=str(age))

my_person = person("Paul", 23)
print(etree.tostring(my_person, encoding="unicode"))
# output: <person age="23" name="Paul"/>
from lxml import objectify
person = objectify.Element("person", name="Paul", age="23")
print(type(person))
# output: <class 'lxml.objectify.ObjectifiedElement'>