TypeError:__class__必须设置为一个类

时间:2019-01-08 11:22:39

标签: python oop inheritance python-2.x

Python版本:2.7.8

点击此处查看:Directory structure


-错误:-

  

TypeError:__class__必须设置为一个类。

此错误发生在Web.py self .__ class__ = Gui_A 中的第7行/第9行(取决于所传递的版本)。


->创建的对象是Web.py <-


other_dir

class BaseParent():
    def test(self):
        pass

Dir / __ init .py __

from other_dir import BaseParent

class Base(BaseParent):
    def login(self):
        pass

Dir / dir1 / gui_a.py

from Dir import Base

class Gui_A(Base):
    def __init__(self):
        super(Gui_A, self).__init__()

Dir / dir1 / gui_b.py

from Dir import Base

class Gui_B(Base):
    def __init__(self):
        super(Gui_B, self).__init__()

Dir / dir2 / Web.py

from Dir.dir1.gui_a import Gui_A
from Dir.dir1.gui_b import Gui_B

class Web():
    def __init__(self, version):
        if version == 'gen1':
            self.__class__ = Gui_A
        elif version == 'gen2':
            self.__class__ = Gui_B


if __name__ == "__main__":
    ob = Web("gen1")

为什么该错误试图指出Gui_A不是类,因此无法进行赋值?

1 个答案:

答案 0 :(得分:1)

如果您混合使用旧式(经典)类和新式类,则在Python 2中会发生此异常。

>>> class A(object):
...     # New style class (inherits from object)
...     pass
... 
>>> class B:
...    # Classic class - does not inherit from object
...    # or any other new-style class
...     def __init__(self):
...         self.__class__ = A
... 
>>> B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: __class__ must be set to a class

旧类和新类实际上是不同的类型:

>>> type(A)
<type 'type'>
>>> type(B)
<type 'classobj'>

所以您不能用一个代替另一个。新样式的类是在Python 2.2中引入的;除非从旧式类继承(我认为标准库中可能仍然有一些),否则任何现代Python 2代码都应专门使用它们。

在Python 3中,旧样式类已被淘汰。因此,在Python 3中,类可以像老式类一样声明。此声明将在Python 2中生成一个旧式类,而在Python 3中生成一个新式类:

class A:
    pass

如果要从Python 3示例创建Python 2代码,请务必意识到这种差异。

相关问题