Building CPython
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat May 16 05:40:55 EDT 2015
On Sat, 16 May 2015 06:08 pm, Marko Rauhamaa wrote:
> Note that almost identical semantics could be achieved without a class.
> Thus, these two constructs are almost identical:
[...]
> IOW, the class is a virtually superfluous concept in Python. Python has
> gotten it probably without much thought (other languages at the time had
> it). I comes with advantages and disadvantages:
Your example is effectively just a way of using closures instead of a class
instance.
Almost anything you can do with classes, you can do with closures. The big
advantage of classes over closures is that you have an interface to access
arbitrary class attributes, while you would need a separate closure for
each and every attribute you want access to.
For example, here is sketch:
class K:
def method(self, arg):
return self.spam + arg
k = K()
the_method = k.method # bound method
as a closure becomes:
def make_closure(instance): # instance is equivalent to self above
def method(arg):
return instance.spam + arg
return method
the_method = make_closure(obj) # Some object with a spam field.
The big advantage of a closure is that you have much more strict
encapsulation. The big disadvantage of a closure is that you have much more
strict encapsulation.
> + improves readability
I wouldn't say that.
> + makes objects slightly smaller
>
> + makes object instantiation slightly faster
Are you sure? Have you actually benchmarked this?
> - goes against the grain of ducktyping
>
> - makes method calls slower
>
> - makes method call semantics a bit tricky
A couple more negatives:
- no such thing as inheritance;
- "is-a" relationship tests don't work;
- an unfamiliar idiom for most people;
Also, at least with Python's implementation, a couple of mixed blessings:
± closures are closed against modification;
± internals of the closure are strictly private;
--
Steven
More information about the Python-list
mailing list