Python TypeError:\类\必须设置为类
Python版本:2.7.8 单击此处查看: -错误:- TypeError:\类\必须设置为类 此错误发生在第7行/第9行,具体取决于在Web.py self中传递的版本Python TypeError:\类\必须设置为类,python,oop,inheritance,python-2.x,Python,Oop,Inheritance,Python 2.x,Python版本:2.7.8 单击此处查看: -错误:- TypeError:\类\必须设置为类 此错误发生在第7行/第9行,具体取决于在Web.py self中传递的版本 ->创建的对象是Web.py的,如果混合使用旧式经典类和新式类,则在Python2中可能会发生此异常 >>> class A(object): ... # New style class (inherits from object) ... pass ... >>> cl
->创建的对象是Web.py的,如果混合使用旧式经典类和新式类,则在Python2中可能会发生此异常
>>> 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
如果您是从Python3示例中创建Python2代码,那么意识到这种差异是很重要的 适用于我的python 2.7.10。请发布一个合适的MCVE和python版本-我们不会仅仅为了测试它而重新创建所有目录结构。提供目录结构是为了让您清楚地了解代码结构,而不是为了在您的终端重新创建目录。谢谢你。
from other_dir import BaseParent
class Base(BaseParent):
def login(self):
pass
from Dir import Base
class Gui_A(Base):
def __init__(self):
super(Gui_A, self).__init__()
from Dir import Base
class Gui_B(Base):
def __init__(self):
super(Gui_B, self).__init__()
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")
>>> 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'>
class A:
pass