Hello,
I am having trouble with throwing class instances around. Perhaps I'm
approaching my goals with the wrong solution, but here's nevertheless a
stripped down example which demonstrates my scenario:
#------------------------------------------------------------------------------------------
class foo:
tests = {}
def __init__( self, id ):
try:
me = self.__class__. tests[ id ]
except KeyError:
print "Did not exist, initializing myself.."
self.attr = "exists"
self.__class__. tests[ id ] = self
else:
print "Already exists! Re-using existing instance"
self = me
print "Me", self.attr + "!" # line 18
def yo(self):
return self.attr # line 21
def main():
a = foo( "test" )
print "ATTR:", a.yo()
b = foo( "test" )
print "ATTR:", b.yo()
if __name__ == "__main__":
main()
#------------------------------------------------------------------------------------------
This is the output:
Did not exist, initializing myself..
Me exists!
ATTR: exists
Already exists! Re-using existing instance
Me exists!
ATTR:
Traceback (most recent call last):
File "cpClass.py ", line 32, in ?
main()
File "cpClass.py ", line 29, in main
print "ATTR:", b.yo()
File "cpClass.py ", line 21, in yo
return self.attr # line 21
AttributeError: foo instance has no attribute 'attr'
#------------------------------------------------------------------------------------------
What the code attempts to do is implementing a, to the API user, transparent
memory-saver by ensuring that no more than one instance of the class foo
exists for a particular id. E.g, the user can simply "create" an instance and
if one not already exists, it is created.
First of all; am I approaching the goal with the right solution?
The way I do fails, obviously. The line 'self = me'(scary..) doesn't really
work for the attribute attr; the attribute exists on line 21, but it fails
when yo() tries to access it. What have failed? Is it a namespace scope
issue? Do 'self = me' do what I think it should?
Cheers,
Frans 13 1959
Frans Englich wrote: What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created.
By the time __init__() is called, a new Foo instance has already been
created. Therefore you need to implement Foo.__new__(). E. g.: class Foo(object):
.... cache = {}
.... def __new__(cls, id):
.... try:
.... return cls.cache[id]
.... except KeyError:
.... pass
.... cls.cache[id] = result = object.__new__( cls, id)
.... return result
.... def __init__(self, id):
.... self.id = id
.... def __repr__(self):
.... return "Foo(id=%r) " % self.id
.... foos = map(Foo, "abca") foos
[Foo(id='a'), Foo(id='b'), Foo(id='c'), Foo(id='a')] foos[0] is foos[-1]
True Foo.cache
{'a': Foo(id='a'), 'c': Foo(id='c'), 'b': Foo(id='b')}
Note that putting the instances into the cache prevents them from being
garbage collected -- you may even end up with higher memory usage.
Use a weakref.WeakVal ueDictionary instead of the normal dict to fix that.
Peter
Frans Englich wrote: Hello,
I am having trouble with throwing class instances around. Perhaps I'm approaching my goals with the wrong solution, but here's nevertheless a stripped down example which demonstrates my scenario:
#------------------------------------------------------------------------------------------
class foo: tests = {} def __init__( self, id ):
try: me = self.__class__. tests[ id ]
except KeyError: print "Did not exist, initializing myself.." self.attr = "exists" self.__class__. tests[ id ] = self
else: print "Already exists! Re-using existing instance" self = me
print "Me", self.attr + "!" # line 18
def yo(self): return self.attr # line 21
As 'self' is a method parameter, changing it only affects the current
function. When __init__ is called, the instance is already created, so
you can't change it.
What you are looking for is a class factory (is this term correct?),
here is a sample implementation (using 2.4 decorators):
class foo:
tests = {}
@classmethod
def get_test(cls, id):
if cls.tests.has_k ey(id):
return cls.tests[id]
else:
inst = cls()
inst.attr = "exists"
cls.tests[id] = inst
return inst
def yo(self):
return self.attr
Here you define get_test as a classmethod, that is, it does not receive
the instance as first argument, but the class. It can be called from the
class (foo.get_test) or an instance (foo().get_test ).
An alternative might be to override __new__, but I'm sure someone other
will suggest this.
Reinhold
"Frans Englich" <fr***********@ telia.com> wrote in message
news:ma******** *************** *************** @python.org... Hello,
[...] What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created.
In other words, you're trying to create a singleton. In general,
singletons are frowned on these days for a number of reasons,
not least because of the difficulty of testing them.
First of all; am I approaching the goal with the right solution?
No. In all Python releases since 2.2, the correct way of doing this is to
use the __new__() method. Unfortunately, the only place it is documented
is here: http://www.python.org/2.2.3/descrintro.html
and here: http://users.rcn.com/python/download/Descriptor.htm
The first reference contains an example of how to do
a singleton: simply search on the word Singleton.
John Roth
Cheers,
Frans
On Monday 17 January 2005 19:02, Peter Otten wrote: Frans Englich wrote: What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created.
By the time __init__() is called, a new Foo instance has already been
created. Therefore you need to implement Foo.__new__(). E. g.: class Foo(object):
... cache = {} ... def __new__(cls, id): ... try: ... return cls.cache[id] ... except KeyError: ... pass ... cls.cache[id] = result = object.__new__( cls, id) ... return result ... def __init__(self, id): ... self.id = id ... def __repr__(self): ... return "Foo(id=%r) " % self.id ...
I'm not sure, but I think this code misses one thing: that __init__ is called
each time __new__ returns it, as per the docs Peter posted.
Cheers,
Frans
On Monday 17 January 2005 20:55, Frans Englich wrote: On Monday 17 January 2005 19:02, Peter Otten wrote: Frans Englich wrote: What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created.
By the time __init__() is called, a new Foo instance has already been
created. Therefore you need to implement Foo.__new__(). E. g.:>> class Foo(object):
... cache = {} ... def __new__(cls, id): ... try: ... return cls.cache[id] ... except KeyError: ... pass ... cls.cache[id] = result = object.__new__( cls, id) ... return result ... def __init__(self, id): ... self.id = id ... def __repr__(self): ... return "Foo(id=%r) " % self.id ...
I'm not sure, but I think this code misses one thing: that __init__ is called each time __new__ returns it, as per the docs Peter posted.
Ahem, John I ment :)
The second typo today..
Cheers,
Frans
On Monday 17 January 2005 20:03, John Roth wrote: "Frans Englich" <fr***********@ telia.com> wrote in message
<snip>
In other words, you're trying to create a singleton. In general, singletons are frowned on these days for a number of reasons, not least because of the difficulty of testing them.
Then I have some vague, general questions which perhaps someone can reason
from: what is then the preferred methods for solving problems which requires
Singletons? Is it only frowned upon in Python code?
Cheers,
Frans
Frans Englich wrote: > >>> class Foo(object): > > ... cache = {} > ... def __new__(cls, id): > ... try: > ... return cls.cache[id] > ... except KeyError: > ... pass > ... cls.cache[id] = result = object.__new__( cls, id) > ... return result > ... def __init__(self, id): > ... self.id = id > ... def __repr__(self): > ... return "Foo(id=%r) " % self.id > ...
I'm not sure, but I think this code misses one thing: that __init__ is called each time __new__ returns it, as per the docs Peter posted.
Ahem, John I ment :)
You are right -- just put the initialization into the __new__() method,
then.
Peter
Frans Englich wrote: On Monday 17 January 2005 20:03, John Roth wrote: "Frans Englich" <fr***********@ telia.com> wrote in message
<snip>
In other words, you're trying to create a singleton. In general, singletons are frowned on these days for a number of reasons, not least because of the difficulty of testing them.
Then I have some vague, general questions which perhaps someone can reason from: what is then the preferred methods for solving problems which requires Singletons? Is it only frowned upon in Python code?
Sorry, no answer here, but do you really want a singleton?
Singleton: "Ensure a class only has one instance, and provide a global point
of access to it"
whereas
Flyweight: "Use sharing to support large numbers of fine-grained objects
efficiently"
as per "Design Patterns" by Gamma et al.
Peter
On Monday 17 January 2005 21:24, Peter Otten wrote: Frans Englich wrote: On Monday 17 January 2005 20:03, John Roth wrote: "Frans Englich" <fr***********@ telia.com> wrote in message
<snip>
In other words, you're trying to create a singleton. In general, singletons are frowned on these days for a number of reasons, not least because of the difficulty of testing them.
Then I have some vague, general questions which perhaps someone can reason from: what is then the preferred methods for solving problems which requires Singletons? Is it only frowned upon in Python code?
Sorry, no answer here, but do you really want a singleton?
Singleton: "Ensure a class only has one instance, and provide a global point of access to it"
whereas
Flyweight: "Use sharing to support large numbers of fine-grained objects efficiently"
as per "Design Patterns" by Gamma et al.
Hehe :) Singleton sounds like what I want, but OTOH I do not know what
Flyweight is, except for sounding interesting. Darn, I really must save for
that Design Patterns by GOF.
Cheers,
Frans This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Josh |
last post by:
Caution, newbie approaching...
I'm trying to come up with a very simple Tkinter test application that
consists of a window with a drop-down menu bar at the top and a grid
of colored rectangles filling the remainder of the window. Mind you,
this is a contrived test application to help me understand Tkinter and
Python, not an actual application yet. I've trivially subclassed
Tkinter.Canvas into ColorCanvas, added a bunch of ColorCanvases...
|
by: Matthew Sims |
last post by:
Python Newbie here. This is my first time learning object-oriented
programming and trying to break out of the usual Korn/Perl/PHP style
of programming. Having some difficulty understand some items.
For lists, I understand this:
C=
print C
some
But I can't seem to do this:
|
by: simonwittber |
last post by:
I know its been done before, but I'm hacking away on a simple Vector
class.
class Vector(tuple):
def __add__(self, b):
return Vector()
def __sub__(self, b):
return Vector()
def __div__(self, b):
return Vector()
|
by: cjfrovik |
last post by:
Has anyone else felt a desire for a 'nochange' value
resembling the 'Z'-state of a electronic tri-state output?
var1 = 17
var1 = func1() # func1() returns 'nochange' this time
print var1 # prints 17
It would be equivalent to:
var1 = 17
|
by: Paul McGuire |
last post by:
I have some places in pyparsing where I've found that the most
straightforward way to adjust an instance's behavior is to change its class.
I do this by assigning to self.__class__, and things all work fine.
(Converting to use of __new__ is not an option - in one case, the change is
temporary, and before the end of the function, I change it back again.)
Any comments on this practice? Is this intended capability for Python
objects, or...
| |
by: John Salerno |
last post by:
Let's say I'm making a game and I have this base class:
class Character(object):
def __init__(self, name, stats):
self.name = name
self.strength = stats
self.dexterity = stats
self.intelligence = stats
self.luck = stats
|
by: Ron Goral |
last post by:
Hello
I am new to creating objects in javascript, so please no flames about my
coding style. =) I am trying to create an object that will represent a "div"
element as a menu. I have written several methods that are working fine. The
problem is if I want to dynamically assign an event handler to the object,
the event handler is not called. What am I doing wrong? Below is a sample
HTML doc with everything in place.
<!DOCTYPE HTML PUBLIC...
|
by: Manuel Graune |
last post by:
Hello,
while trying to learn how to program using objects in python (up to now
simple scripts were sufficient for my needs) I stumbled over the
a problem while assigning values to an object.
The following piece of code shows what I intend to do:
<---snip--->
|
by: The Pythonista |
last post by:
I've been wondering for a while about whether assigning to __class__ is
bad form or not. Specifically, I mean doing so when some other method of
implementing the functionality you're after is available (i.e. using an
adapter, or something like the strategy pattern).
To give an example and a non-example of what I'm talking about, consider
the following recipes from the online Python Cookbook:
Ring Buffer:...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |