changing how instances are "created"

newseater kbilsted at hotmail.com
Sun Jun 12 20:00:40 EDT 2005


> > class Creator
> > def createInstance(cls, *args, **kwargs):
> > anewinstance = cls.__new__(cls, *args, **kwargs)
> > anewinstance.__init__(*args, **kwargs)
> >
> > return anewinstance
> > createInstance = staticmethod(createInstance)
> >
> >
> > can anyone help??
>
> __new__ is the proper way to do this, but making it work
> is a bit tricky. If you could post the code you tried to
> get to work for __new__(), we could critique it.
>
> The current documentation is in 3.3.1 of the Python
> Reference Manual (Python 2.4 version). In earlier
> versions, there were a couple of other documents
> that did a better (IMO) job of explaining things.
>
> The trick is that __new__ must return an instance.
> It can be a newly created instance (and the doc shows
> how to do this) or an existing instance of any new style
> class.

from the documentation it was very hard to guess what the "..." was
supposed to be. also i wasn't able to find out how to control if
__init__() would be called on an instance (if i reused that instance..
and that instance could be of a completely different type).

eg. i didn't get much out of
http://docs.python.org/ref/customization.html

from http://gnosis.cx/publish/programming/metaclass_1.html

i get

>>> class ChattyType(type):
...     def __new__(cls, name, bases, dct):
...         print "Allocating memory for class", name
...         return type.__new__(cls, name, bases, dct)
...     def __init__(cls, name, bases, dct):
...         print "Init'ing (configuring) class", name
...         super(ChattyType, cls).__init__(name, bases, dct)
...
>>> X = ChattyType('X',(),{'foo':lambda self:'foo'})
Allocating memory for class X
Init'ing (configuring) class X
>>> X, X().foo()
(<class '__main__.X'>, 'foo')


but that way of creating objects is just plain silly!
(the X = Chattype('X'.....)
and where are the arguments to __init__() passed?? maybe i want to
change those as well.... this is partly why i wanted to use an external
class for the creation.

I tried looking at the __new__ buildin but this seems to be addressing
old-style objects (which i'm not interested in using)



>
> By the way - when you post code, please use spaces
> for indentation. There are a number of popular mail
> clients that don't play fair with tabs, and people using
> these clients will frequently ignore code that isn't
> properly indented.

sorry. maybe people should complain to those lousy newsreader authors
instead of everyone having to comply to the lowest standards? I guess
the readers are actually un*x readers although your comment typically
is found in the w*ndows world where everyone is forced into using word
:-)


> John Roth




More information about the Python-list mailing list