gpt4 book ai didi

Python:重新定义了原始 'object' 类。如何取回 'object' 类?

转载 作者:行者123 更新时间:2023-11-28 20:09:40 29 4
gpt4 key购买 nike

我正在为 Squish 自动化工具使用 python 语言。这个工具用一些自定义对象和函数扩展了 python。这就是他们在 manual 中所说的:

Squish's Python-specific extension modules are loaded automatically by internally executing the equivalent of the following statements:

Python
import test
import testData
import object
import objectMap
import squishinfo
from squish import *

This means that it is not necessary to import them yourself unless you are developing your own standalone module.

这样做他们自动重新定义object(到this),所以我尝试做新式类(比如class NewClass(object ): ) 给我一个错误:

TypeError: Error when calling the metaclass bases. module.__init__() takes at most 2 arguments (3 given)

所以我试图取回对象。看完the amazing article about metaclasses我正在尝试使用以下代码获取 object:

class OrigObject:
__metaclass__ = type

class NewClass(OrigObject):
pass

我的问题是:这与从原始 object 类继承一样吗?

更新:我只能使用 Python 2.4(如果重要的话)

谢谢!

最佳答案

从您链接的页面:

Squish's object module has the same name as the base class of all Python 2 new-style classes, and of all Python 3 classes. In practice this is very rarely a problem. For Python 2 we can just create old-style classes or do import __builtin__ and inherit from __builtin__.object instead of object. For Python 3 there is no need to do anything since we don't ever explicitly inherit object since it is inherited by default if no other class is specified.

所以:

>>> import __builtin__
>>> __builtin__.object
<type 'object'>
>>> class SomeOldStyleClass():
... pass
...
>>> SomeOldStyleClass.__subclasses__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class SomeOldStyleClass has no attribute '__subclasses__'
>>> class SomeClass(__builtin__.object):
... pass
...
>>> SomeClass.__subclasses__()
[]

不过,我要指出的是,我认为这是该模块的创建者的一个非常糟糕的决定,他们应该给它起别的名字。即使它针对的是 Python 3.x,如果他们是为 2.x 分发它,他们也应该考虑一下,将它命名为其他名称并通过调用它对他们没有任何伤害 object 他们制造问题。

关于Python:重新定义了原始 'object' 类。如何取回 'object' 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10281984/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com