简体   繁体   中英

Best practice for Python 3 class creation

In my research I found that in Python 3 these three types of class definition are synonymous:

class MyClass:
    pass

class MyClass():
    pass

class MyClass(object):
    pass

However, I was not able to find out which way is recommended. Which one should I use as a best practice?

I would say: Use the third option:

class MyClass(object):
    pass

It explicitly mentions that you want to subclass object (and doesn't the Zen of Python mention: "Explicit is better than implicit.") and you don't run into nasty errors in case you (or someone else) ever run the code in Python 2 where these statements are different .

In Python 2, there's 2 types of classes . To use the new-style, you have to inherit explicitly from object . If not, the old-style implementation is used.

In Python 3, all classes extend object implicitly, whether you say so yourself or not.

You probably will want to use the new-style class anyway but if you code is supposed to work with both python 2 and 3 you'll have to explicitly inherit from object:

class Foo(object):
    pass 

To jump on the other answer, yes the Zen of Python state that

Explicit is better than implicit.

I think this mean we should avoid possible confusion in code like we should in language in general, remember code is communication.

If you only work with python 3, and your code/project explicitly state that, there is no possible confusion, all class without explicit inheritance automatically inherit from object . If for some obscure reason the base class change in the future (let's imagine from object to Object ), the same code will work. And the Zen of Python also says that

Simple is better than complex.

(of course complex is quite an overstatement in this example but still...)

So again if you code only support python3, you should use the simplest form:

class Foo:
    pass

The form with just () is quite useless since it doesn't give any valuable information.

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