What is the semantics meaning of 'object'?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Jun 22 23:20:02 EDT 2013
On Sat, 22 Jun 2013 19:58:38 -0700, Adam wrote:
> class FooBar(object):
> def __init__(self):
> ...
>
> Inheritance usually takes a class name to indicate which class is the
> 'parent' class. However, in the previous example, from a django book,
> the class actually takes an 'object' like parameter, doesn't it? What is
> the semantics meaning of such kind of notation?
It's not merely notation, "object" is the name of a class. If you type it
(without quotes) at the interactive interpreter, you will see it is a
built-in class:
py> object
<class 'object'>
In Python 3, the use of object as base class is optional, but in Python 2
there is a subtle difference between classes that inherit from object and
those that don't. The reason for this difference is buried in the mists
of time, going back to Python 2.2. If you are interested, google on
"Python unifying types and classes":
https://duckduckgo.com/html/?q=Python+unifying+types+and+classes
As a general rule, unless you actually want "old-style class" behaviour,
you should always inherit from object (or some other built-in type) in
Python 2. In Python 3, it doesn't matter.
The differences include:
* property only works in "new-style" classes that inherit from object;
* likewise for super;
* multiple inheritance with old-style classes can be buggy;
* new-style classes may be slightly faster in general;
* on the down side, automatic delegation of special double-underscore
methods like __getitem__ and __str__ doesn't work with new-style classes.
If none of this means anything to you, be glad, and just inherit from
object or some other built-in type in all your classes, and all will be
good.
--
Steven
More information about the Python-list
mailing list