简体   繁体   English

将旧式类重写为新类

[英]Rewrite old-style classes as new ones

I ran pylint on some code and got a complaint about old-style classes.我在一些代码上运行 pylint 并收到了关于旧式类的抱怨。

Can I rectify this by simply changing:我可以通过简单地改变来纠正这个问题:

class MyClass:

to:到:

class MyClass(object):

Or is there something more involved?或者还有什么更重要的事情?

In Python 2, writing在 Python 2 中,编写

class MyClass(object):

would suffice.就足够了。 Or you switch to Python 3, where或者你切换到 Python 3,其中

class MyClass:

would be just fine.就好了。

The inheritance list usually gives a list of base classes (see Customizing class creation for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing.继承列表通常会给出一个基类列表(请参阅自定义类创建以获得更高级的用途),因此列表中的每一项都应评估为允许子类化的类对象。 Classes without an inheritance list inherit, by default, from the base class object;没有继承列表的类默认从基类对象继承; hence因此

class Foo:
    pass

is equivalent to相当于

class Foo(object):
    pass

See also: https://docs.python.org/3/reference/compound_stmts.html#class另见: https : //docs.python.org/3/reference/compound_stmts.html#class

Also, as @Kevin pointed out in a comment, method resolution is not trivial and might lead to unexpected behavior when using multiple inheritance: http://python-history.blogspot.com/2010/06/method-resolution-order.html此外,正如@Kevin 在评论中指出的那样,方法解析并非微不足道,在使用多重继承时可能会导致意外行为: http : //python-history.blogspot.com/2010/06/method-resolution-order.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM