473,898 Members | 3,274 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__getitem__ on new-style classes

What i'm trying to do is tie special methods of a "proxy" instance
to another instance:

def test1():
class Container:
def __init__( self, data ):
self.data = data
self.__getitem_ _ = self.data.__get item__

data = range(10)
c = Container(data)
print "test1"
print c[3]

This works OK. But when I try the same thing on
new style classes:

def test2():
print "test2"
class Container(objec t):
def __init__( self, data ):
self.data = data
# self.__dict__["__getitem_ _"] = self.data.__get item__
self.__setattr_ _( "__getitem_ _", self.data.__get item__ )
data = range(10)
c = Container(data)
print
print c.__getitem__(3 ) # works OK
print c[3] # fails

I get a "TypeError: unindexable object". It
seems that c[] does not call __getitem__ in this case.

The plot thickens, however, when one tries the following:

def test3():
data = range(10)
c = type( "Container" , (), { "__getitem__":d ata.__getitem__ } )()
print "test3"
print c[3]

Which works fine. However, if I need to resort to
such trickery, no-one here where i work will have any idea
what it does :)

Would anyone like to shed some light on what is going on here ?

bye,

Simon.

Jul 18 '05 #1
1 1986
si***@arrowtheo ry.com wrote:
What i'm trying to do is tie special methods of a "proxy" instance
to another instance: .... new style classes:

def test2():
print "test2"
class Container(objec t):
def __init__( self, data ):
self.data = data
# self.__dict__["__getitem_ _"] = self.data.__get item__
self.__setattr_ _( "__getitem_ _", self.data.__get item__ )
data = range(10)
c = Container(data)
print
print c.__getitem__(3 ) # works OK
print c[3] # fails

I get a "TypeError: unindexable object". It
seems that c[] does not call __getitem__ in this case. because __getitem__ is looked up in the class, not the instance dictionary
The plot thickens, however, when one tries the following:

def test3():
data = range(10)
c = type( "Container" , (), { "__getitem__":d ata.__getitem__ } )()
print "test3"
print c[3]


Here you've created an entry in the class dictionary, just like writing
data = range(10)
class Container(objec t):
__getitem__ = data.__getitem_ _

but, this probably doesn't help you much if you want the method to delegate to
an attribute of the instance, since the instance is unavailable at class
definition time

So, one solution, is to use create a delegating descriptor, like so:

class Delegate(object ):
def __init__(self, attrname):
self.attrname = attrname
def __get__(self, obj, cls):
if isinstance(obj, cls):
# Note that the attribute is looked up on obj._data
return getattr(obj._da ta, self.attrname)
else:
return self

class Example(object) :
__getitem__ = Delegate("__get item__")

def __init__(self, delegate):
self._data = delegate
e = Example(range(1 0))
e[3]

3
Michael
Jul 18 '05 #2

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

Similar topics

4
8034
by: KanZen | last post by:
I'm trying to understand the difference between __setitem__ and an ordinary method. For example: >>> class A(object): def __getitem__(self, *args): print len(args) def normalMethod(self, *args): print len(args) >>> a=A()
0
1320
by: Karl Chen | last post by:
Hi. Is it possible to make a classmethod out of __getitem__? I.e. I want to do: class C: def __getitem__(p): return 1+p
7
2302
by: Steven Bethard | last post by:
So, GvR said a few times that he would like to get rid of lambda in Python 3000. Not to start up that war again, but I'm trying to eliminate unnecessary lambdas from my code, and I ran into a case using unittest.TestCase that I don't really know how to deal with. Previously, I had written some code like: self.assertRaises(ValueError, lambda: method(arg1, arg2)) This was a simple fix because assertRaises takes *args and **kwds, so
0
1161
by: It's me | last post by:
I've built a Python application using PythonCard 1.9 and Python 2.3 running under Windows XP. Everything works except that when I use the keyboard instead of the mouse to do certain operations in a data entry field (like Shift-Home), the program stops at line 1014 of wx-2.5.3-msw.ansi\wx\_core.py. def __getitem__(self, index): try: x = self.Get() except IndexError:
3
5964
by: Tobiah | last post by:
#!/usr/bin/python # Hi, # # I noticed something interesting when trying to define # the __getitem__() method in a class that inherits from # (dict). If within the __getitem__ method I attempt # to get an item from self, the __getitem__ method is # called in an infinite recursion. I am very fond of # inheriting from (dict) as in the class 'bar' below,
7
2338
by: David Isaac | last post by:
I have a subclass of dict where __getitem__ returns None rather than raising KeyError for missing keys. (The why of that is not important for this question.) I was delighted to find that __contains__ still works as before after overriding __getitem__. So even though instance does not raise KeyError, I still get (as desired) 'key' in instance == False. Looking forward:
2
1443
by: Giovanni Bajo | last post by:
Hello, given the following object: .... def __getitem__(self, idx): .... if idx >= 10: raise IndexError .... return idx .... def __len__(self): .... return 10 ....
0
1053
by: dackz | last post by:
>>class ListyThing(list): pass .... Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError <type 'list'> I don't find this intuitive. Is this intentional? I believe this could be avoided if list.__getitem__ used "self.__class__()" to make a new instance, instead of "list()", but I don't know how that works under
3
2074
by: tsm8015 | last post by:
I do not think I am understanding how to redefine the getitem function for string. Why does the following not work: class NStr(str): def __getitem__(self,idx): print "NStr:getitem",idx,type(idx) return str.__getitem__(self,idx) s=NStr("abcde")
6
3595
by: Andreas Matthias | last post by:
The following code doesn't run but I hope you get what I am trying to do. class my_dict (dict): def __getitem__ (self, key, crazy = False): if crazy == True: return 5 * self.get(key) else:
0
9993
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
11259
Oralloy
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...
0
10857
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...
0
10483
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
9661
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
8035
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
5880
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...
1
4706
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
2
4295
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.