Was just thinking about Python's dict
"function" and starting to realize that dict
isn't really a function at all. For example, if we do dir(dict)
, we get all sorts of methods that aren't include in the usual namespace of an user defined function. Extending that thought, its similar to dir(list)
and dir(len)
. They aren't function, but really type
s. But then I'm confused about the documentation page, http://docs.python.org/2/library/functions.html, which clearly says functions. (I guess it should really just says builtin callables)
So what gives? (Starting to seem that making the distinction of classes and functions is trivial)
It's a callable, as are classes in general. Calling dict()
is effectively to call the dict constructor. It is like when you define your own class (C
, say) and you call C()
to instantiate it.
One way that dict
is special, compared to, say, sum
, is that though both are callable
, and both are implemented in C (in cpython, anyway), dict
is a type
; that is, isinstance(dict, type) == True
. This means that you can use dict
as the base class for other types, you can write:
class MyDictSubclass(dict):
pass
but not
class MySumSubclass(sum):
pass
This can be useful to make classes that behave almost like a builtin object, but with some enhancements. For instance, you can define a subclass of tuple
that implements +
as vector addition instead of concatenation:
class Vector(tuple):
def __add__(self, other):
return Vector(x + y for x, y in zip(self, other))
Which brings up another interesting point. type
is also implemented in C. It's also callable. Like dict
(and unlike sum
) it's an instance of type
; isinstance(type, type) == True
. Because of this weird, seemingly impossible cycle, type
can be used to make new classes of classes, (called metaclasses). You can write:
class MyTypeSubclass(type):
pass
class MyClass(object):
__metaclass__ = MyTypeSubclass
or, in Python 3:
class MyClass(metaclass=MyTypeSubclass):
pass
Which give the interesting result that isinstance(MyClass, MyTypeSubclass) == True
. How this is useful is a bit beyond the scope of this answer, though.
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