473,714 Members | 2,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assigning to self


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


Jul 18 '05 #1
13 1944
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
Jul 18 '05 #2
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
Jul 18 '05 #3
"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


Jul 18 '05 #4
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

Jul 18 '05 #5
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

Jul 18 '05 #6
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

Jul 18 '05 #7
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

Jul 18 '05 #8
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

Jul 18 '05 #9
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

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5980
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...
10
1820
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:
8
1398
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()
7
1195
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
4
6567
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...
16
1935
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
7
2531
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...
5
1657
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--->
1
1526
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:...
0
8797
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, 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...
0
9171
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9071
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9010
tracyyun
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...
0
7946
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6629
isladogs
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...
0
4462
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4717
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2514
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.