简体   繁体   中英

Rewrite old-style classes as new ones

I ran pylint on some code and got a complaint about old-style classes.

Can I rectify this by simply changing:

class MyClass:

to:

class MyClass(object):

Or is there something more involved?

In Python 2, writing

class MyClass(object):

would suffice. Or you switch to Python 3, where

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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