Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 557
Bentley4 Avatar asked Apr 06 '12 13:04

Bentley4


People also ask

What is class classname object in Python?

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.

What is object in class object in Python?

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.

Is object a keyword in Python?

It is not a keyword.

Is object a type in Python?

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.


2 Answers

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.

like image 172
Marcin Avatar answered Sep 30 '22 01:09

Marcin


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.

like image 42
prosti Avatar answered Sep 30 '22 01:09

prosti