相关疑难解决方法(0)

Python中的旧样式和新样式类有什么区别?

Python中的旧样式和新样式类有什么区别?我什么时候应该使用其中一种?

python oop types class new-style-class

953
推荐指数
8
解决办法
22万
查看次数

从builtins导入对象只影响一个类

我正在newstyle使用python2将代码从python2转换为python3 future.我的项目是Django 1.11

我在forms.py中有一个类:

class Address:
    ...rest of code...

class AddressForm(Address, forms.ModelForm):
    ...rest of code...
Run Code Online (Sandbox Code Playgroud)

在Python 2中

转换为:

from buitlins import object
class Address(object):
        ...rest of code...

class AddressForm(Address, forms.ModelForm):
    ...rest of code...
Run Code Online (Sandbox Code Playgroud)

在Python 3中

我有一个selenium测试,在转换为Python3后调用此Form时失败,并出现以下错误:

File "<path_to_venv>/local/lib/python2.7/site-packages/django/utils/six.py", line 842, in <lambda>
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
File "<path_to_venv>/local/lib/python2.7/site-packages/future/types/newobject.py", line 78, in __unicode__
s = type(self).__str__(self)
RuntimeError: maximum recursion depth exceeded
Run Code Online (Sandbox Code Playgroud)

但是,当我删除导入时from buitlins import object,测试通过.

但是,由于我添加了一个未来的检查,我得到了一个未来的差异错误,因此每个班级都必须转换为newstyle.我希望它可以在Python2和Python3中工作.

有没有办法这个模块builtins模块导入只能影响一个类而不影响forms.py文件中的其他类.还是有其他方法来处理这个?

python future new-style-class python-2.7 python-3.x

6
推荐指数
1
解决办法
192
查看次数

标签 统计

new-style-class ×2

python ×2

class ×1

future ×1

oop ×1

python-2.7 ×1

python-3.x ×1

types ×1