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?
Python is an object-oriented programming language, and almost everything is an object, with its properties and methods. In Python, use the type(object) function to return a type object. To access the classname of the type of the object, use the __name__ attribute.
An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object. We can think of a class as a sketch (prototype) of a house.
It is not a keyword.
Everything in Python is an object including classes. All classes are instances of a class called "type". The type object is also an instance of type class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With