Copy constructors
Guido van Rossum
guido at python.org
Sun Aug 12 13:26:49 EDT 2001
Roeland Rengelink <r.b.rigilink at chello.nl> writes:
> One idiom where I use __class__ assignment is the following
>
> class State1:
> def do_something(self):
> ...do something...
> def change_state(self):
> self.__class__ = State2
> class State2:
> def do_something(self):
> ...do something else...
> def change_state(self):
> self.__class__ = State1
But you can easily do this differently -- e.g. you could do a method
assignment, or you could represent the state by an object.
> Speaking of __new__. Would it be an idea to give __new__() the
> responsibility for calling __init__ on the new instance.
I have thought about this. It would be less flexible, so I think not.
For example, with the current set-up you can use __new__ to create an
uninitialized instance, bypassing __init__. If __new__ called
__init__, you couldn't do that.
> BTW, I managed to build a Singleton class, using metaclasses, that gave
> me the right behaviour. This process has become slightly less painfull
> in 2.2, but only slightly ;)
A new metaclasses is a good way to implement a singleton pattern. A
factory function is also a good way.
> The Singleton pattern is a rather trivial example of course.
(I think the singleton pattern has received way too much exposure for
such a trivial idea.)
> I think one of things I'm looking for here is the ability to fold
> functionality, that I would traditionally put in factory functions,
> into a base class.
To some extent, you can do that -- but you'll have to forego __init__
of you want __new__ to return old instances (or write __init__ so that
it can be called more than once).
> __new__ seems to be ideally suited for that, but I would need to
> have control over calling __init__ too. Having said that, being able
> to play these tricks with metaclasses, is fun too. In a perverse
> sort of way...
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list