By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,199 Members | 1,120 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,199 IT Pros & Developers. It's quick & easy.

changing how instances are "created"

P: n/a
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??

Jul 19 '05 #1
Share this Question
Share on Google+
7 Replies


P: n/a
newseater wrote:
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
rk***@ucsd.edu

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

Jul 19 '05 #2

P: n/a


Robert Kern wrote:
newseater wrote:
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.


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

Jul 19 '05 #3

P: n/a
"newseater" <kb******@hotmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
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

Jul 19 '05 #4

P: n/a
newseater wrote:

Robert Kern wrote:
newseater wrote:
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.


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
rk***@ucsd.edu

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

Jul 19 '05 #5

P: n/a
> > 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


Jul 19 '05 #6

P: n/a
>
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...

Jul 19 '05 #7

P: n/a

"newseater" <kb******@hotmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
> 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).


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.
eg. i didn't get much out of
http://docs.python.org/ref/customization.html

from http://gnosis.cx/publish/programming/metaclass_1.html
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

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


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
John Roth


Jul 19 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.