What do you call a class not intended to be instantiated
Terry Reedy
tjreedy at udel.edu
Mon Sep 22 14:36:03 EDT 2008
Steven D'Aprano wrote:
>
> Consider a factory function:
>
> def factory(x): # a toy example
> alist = [x]
> def foo():
> return alist
> return foo
>
>
> Now suppose we "instantiate" the factory (for lack of a better term):
>
>>>> f1 = factory(0)
>>>> f2 = factory(0)
Your factory is returning closures. This is the functional equivalent
of a class returning instances.
class factory(object):
def __init__(self, x):
self.alist = [x]
def __call__(self):
return self.alist
> Even though f1 and f2 have the same behaviour, they are obviously not the
> same object. And although both return a list [0], it is not the same list:
>
>>>> f1() == f2() == [0]
> True
>>>> f1() is f2()
> False
same results
> They have a (very little) amount of state, which is *not* shared:
>
>>>> L = f1()
>>>> L.append(1)
>>>> f1()
> [0, 1]
>>>> f2()
> [0]
same results
> But there's only a limited amount of state that functions carry around.
That is why Python has class statements.
> And instances share at least some state, by virtue of having the same
class.
If the only class attributes are methods and you do mutate the class,
then the fact that f1.__class__ is f2.__class__ is not really shared state.
[from a later post]
>But that's precisely what I want to avoid: I don't want the objects to
share *any* state, not even their class.
Unless you can show how sharing an immutable __class__ attribute is an
actual impediment, this strike me as artificial pedantry and unnecessary
self handcuffing. And you obviously can make that attribute effectively
immutable by ignoring it and also not changing the class itself. It is
just internal, implementation-defined bookkeeping.
The identity of immutable objects is irrelevant. If part of your
'unshared state' for each instance were a string, and two instances
happened to have the same string value, would you be upset because the
interpreter happened to use the same string object instead of two string
objects with the same value? Ditto for numbers, tuples, and so on.
Terry Jan Reedy
More information about the Python-list
mailing list