class Classname(object), what sort of word is 'object' in Python?

自闭症网瘾萝莉.ら 提交于 2019-12-18 18:48:33

问题


When I create a module with its sole content:

class Classname(randomobject):
    pass

And I try to run the .py file of the module the interpreter says that randomobject is not defined.

But when I do:

class Classname(object):
    pass

The module runs just fine. So if object is not a keyword, then what is it?


回答1:


object is a (global) variable. By default it is bound to a built-in class which is the root of the type hierarchy.

(This leads to the interesting property that you can take any built-in type, and use the __bases__ property to reach the type called object).

Everything built-in that isn't a keyword or operator is an identifier.




回答2:


object is an identifier that refers to a builtin type.

Unlike many other languages, there are no primitive types in Python. Everything is an object, including all data types.

I'm not sure why you expected inheriting from randomobject to work.




回答3:


object is the base class from which you inherit when creating a new-style class in Python 2.




回答4:


The following three class declarations are identical in Python 3

class Classname(object):
    pass

class Classname():
    pass

class Classname:
    pass

Well, there will be minor differences, but not fundamentally important since the object class is the base for all.

If you plan to write Python agnostic code (Python2 and Python3 agnostic) you may use the first declaration.



来源:https://stackoverflow.com/questions/10044321/class-classnameobject-what-sort-of-word-is-object-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!