How to define what a class is ?
ben+python at benfinney.id.au
Wed Feb 24 04:11:36 EST 2016
"ast" <nomail at invalid.com> writes:
> Since a class is an object, I ask myself how to define rigorously what
> a class is.
A class is a type. This bears stating, because for a large part of
Python's history, the two were distinct.
A lot of Python documentation that has its roots in that history still
is careful to maintain the distinction, which in current Python is
Every type (and therefore every class) is a template for instances. The
type defines what values are possible for those instances, and also
defines what behaviour those instances will have in common.
> classes are instances from type, but not all, since a class may be an
> instance of a metaclass
Yes. Every class (every type) is an instance of a metaclass, and there
is a particular metaclass named ‘type’.
> A class is always callable
By default, calling a class creates an instance of that class, and
returns that instance to the caller.
> A class inherit from some others classes, so they have a bases
That's not part of the definition, really. You need to know that, but
it's not necessary to say what a class is.
> any thing else ?
See the reference documentation on this topic
> Suppose I provide to you an object and that I ask to you to tell me if
> it is a class or not. How would you proceed ?
If the object is an instance of the ‘type’ metaclass, the object is a
type (i.e. a class).
Metaclasses are callable, and return a type (a class) to the caller.
The ‘type’ metaclass, if called with an object as a parameter, will
return the type of that object.
If you have the name ‘foo’ bound to an object, you can call::
and the metaclass ‘type’ will return the instance of that object's type.
If you want a boolean test::
>>> isinstance(3, type)
>>> isinstance("spam", type)
>>> isinstance(int, type)
>>> isinstance(type, type)
\ “The fact of your own existence is the most astonishing fact |
`\ you'll ever have to confront. Don't dare ever see your life as |
_o__) boring, monotonous, or joyless.” —Richard Dawkins, 2010-03-10 |
More information about the Python-list