changing how instances are "created"

N

newseater

Hello. I need to be able to control how objects are created. Sometimes
when creating an object, i want to reuse another object instead. I've
searched for factory method implementations and singleton
implementations. They were too much of a hack!

My first attempt of doing this was to play around with the __new__()
method. But i didn't quite succed. Then i came up with making a static
method which can create my instances or re-use other instances.
However, the below code I cannot get to work :(

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??
 
R

Robert Kern

newseater said:
Hello. I need to be able to control how objects are created. Sometimes
when creating an object, i want to reuse another object instead. I've
searched for factory method implementations and singleton
implementations. They were too much of a hack!

My first attempt of doing this was to play around with the __new__()
method. But i didn't quite succed. Then i came up with making a static
method which can create my instances or re-use other instances.
However, the below code I cannot get to work :(

class Creator
def createInstance(cls, *args, **kwargs):
anewinstance = cls.__new__(cls, *args, **kwargs)
anewinstance.__init__(*args, **kwargs)

return anewinstance
createInstance = staticmethod(createInstance)

You want a classmethod, not a staticmethod.

--
Robert Kern
(e-mail address removed)

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
 
N

newseater

Robert said:
You want a classmethod, not a staticmethod.

why do i want that? how should the code look like? currently the
objects fail to get initialized etc...
 
J

John Roth

newseater said:
Hello. I need to be able to control how objects are created. Sometimes
when creating an object, i want to reuse another object instead. I've
searched for factory method implementations and singleton
implementations. They were too much of a hack!

My first attempt of doing this was to play around with the __new__()
method. But i didn't quite succed. Then i came up with making a static
method which can create my instances or re-use other instances.
However, the below code I cannot get to work :(

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.

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.

John Roth
 
R

Robert Kern

newseater said:
why do i want that? how should the code look like? currently the
objects fail to get initialized etc...

A staticmethod does not take a cls argument. It is essentially just a
function that is attached to a class.

class Something(object):
def foo(x, y, z):
print x, y, z
foo = staticmethod(foo)

A classmethod does that a cls argument.

class Creator(object):
def createInstance(cls, *args, **kwds):
pass
createInstance = classmethod(createInstance)

As for the desired content of the classmethod, I don't care to
speculate. I usually just use the Borg pattern or a factory or any one
of the Singleton implementations floating around. They are no more hacky
than this, but they have the added benefit of working.

--
Robert Kern
(e-mail address removed)

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
 
N

newseater

class Creator
__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
.... 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)
....Allocating memory for class X
Init'ing (configuring) class X(<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
:)
 
N

newseater

A staticmethod does not take a cls argument. It is essentially just a
function that is attached to a class.

yes i know of that difference... but one cannot easily override a class
method in a supclass.. as calling super then make the cls variable
point to the super class class rather than the subclass! very
confusing! So i decided to skip that one...
 
J

John Roth

newseater said:
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).

I believe that __init__() is not called if the instance is not of
the same type as the class with the __new__() method.

There was a thread on that not too long ago, and I believe
that was the resolution: the docs were wrong, __init__ is
only called if the returned instance is for the class with the
__new__ method. The 2.4 docs seem to say it properly.

This has nothing to do with metaclasses. Wandering into
that will fry your brain.

....
but that way of creating objects is just plain silly!

Yep. If you don't need a metaclass, don't use one. Metaclasses
are a special purpose construct. If you need it, you'll know that
you need it. Othewise you don't, and you certainly don't here.
I tried looking at the __new__ buildin but this seems to be addressing
old-style objects (which i'm not interested in using).

__new__ is only invoked for new style classes; it is not invoked
for old style classes.f

The following may be helpful: it's a relatively extended article
on new style classes that was left out of the 2.4 references
because the content had supposedly been absorbed into the
mainline documentation.

http://www.python.org/2.2.3/descrintro.html

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
:)

This dead horse has been beaten into a pulp many times. People
with newsreaders and mail clients that don't play fair with tabs are
not going to change; snide remarks will only reflect on the person
making the remark.

The major problem is IE, although I've seen other newsreaders
and mail clients do the same thing. Also, I don't even have Word
on my Windows system; I use Open Office. Being "forced" to
use Word is a choice.

John Roth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top