473,386 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

changing how instances are "created"

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
7 1356
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


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
"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
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
> > 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
>
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

"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Jason | last post by:
Given a scenario where I'm monitoring a folder, once the file has been created, I'd like to have it relocated to another folder via the File.Copy() method. My problem occurs when I paste a...
3
by: Tomdhu | last post by:
As a Newbie I've picked up a heap of tips and tricks from this NG but I have been battling to get the current user's Netwok Login ID recorded on a form at the time a new record is created or...
3
by: EYIII | last post by:
Is it possible to retrieve the "created by" identity and "modified by" identity for a file (e.g. word doc, .pdf, report, etc) using .NET?
0
by: Andy B | last post by:
When I ran the asp.net admin tool to setup web application settings, I get the following notice when I went to profile and chose to use a single provider for all features: "The provider wasn't...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.