473,782 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class __getitem__ when item is not a sequence ???

Sorry for the vague subject. Not sure what the right terminology is.

How can I use an instance's data by reference to the instance name,
not the instance attribute? OK the question is probably really poor
but hopefully an example will make it clear.
x=1
type(x)
<type 'int'>
x.__add__(1)
2
print x
1
3*x
3

In this case x is an integer. My understanding is that x in an
instance of an integer class. Since it refers to only a single value
things like print x, 3*x etc operate on the instance name which seems
to refer to the instance data, not the instance itself. I want to do
the same for my own classes.

For example:
class y:
def __init__(self,v al):
self.val = val
y1 = y(10)
print y1
<__main__.y instance at 0x043C7B20>
3*y1
<type 'exceptions.Typ eError'>: unsupported operand type(s) for *:
'int' and 'instance

I have been able to do this by overriding __getitem__ when self.val is
a sequence. But I can't find out what to do when self.val is a simple
type like int, float etc.

Apr 19 '07 #1
2 1417
On Thu, 19 Apr 2007 16:47:55 -0700, cfriedalek wrote:
Sorry for the vague subject. Not sure what the right terminology is.

How can I use an instance's data by reference to the instance name,
not the instance attribute? OK the question is probably really poor
but hopefully an example will make it clear.
>x=1
type(x)
<type 'int'>
>x.__add__(1)
2
>print x
1
>3*x
3

In this case x is an integer. My understanding is that x in an
instance of an integer class. Since it refers to only a single value
things like print x, 3*x etc operate on the instance name which seems
to refer to the instance data, not the instance itself.
No, names are separate from instances. Instances don't know what
name(s) they have been called. Everything in Python is an object, so you
can think of it like this...

Here's an int:
<int, 7>

Python knows that instance as the literal 7, so any time you write 7 in
your code, that tells Python to use that specific instance.

When you write "x = 7" that tells Python to bind the _name_ "x" to the
instance 7. But notice that the instance itself doesn't know what
name, or names, it is bound to. In fact, there may be no name at all.

When you say "x.__add__( 1)" Python looks up the name "x", finds that it is
the instance 7, and then calls 7.__add__(1). And yes, you can write that,
although you have to sneak a space between 7 and the dot so it doesn't
look like a float:
>>7 .__add__(1) # the long way of writing 7+1
8

Now, you might be thinking that ints have an attribute like "value", and
that x.__add__(1) does something like this:

def __add__(self, other):
return self.value + other

That's what you will probably do for custom classes that you create
yourself, but that's not what ints do. They understand how to do addition
"magically" . 7.__add__(1) knows the answer is 8 (because under the hood
it does arithmetic on bits) and it returns the instance 8, creating it if
it doesn't already exist.

I want to do
the same for my own classes.

For example:
>class y:
def __init__(self,v al):
self.val = val
>y1 = y(10)
print y1
<__main__.y instance at 0x043C7B20>
>3*y1
<type 'exceptions.Typ eError'>: unsupported operand type(s) for *:
'int' and 'instance

I have been able to do this by overriding __getitem__ when self.val is
a sequence.
How did you do that?

But I can't find out what to do when self.val is a simple
type like int, float etc.
In the same way that the + operator is turned into the __add__ method, the
* operator is turned into __mul__.

y1*3 =y1.__mul__(3)
3*y1 =y1.__rmul__(3)

Can you see why you need both a __mul__ and a __rmul__ operator?
Here is a simple way to do what I think you want:

class Y:
# the convention is the class names start with a capital letter
def __init__(self,v al):
self.val = val # assume val is an int
def __mul__(self, other):
value = self.val*other
# Now value will be an int; if you are happy with that,
# just "return value".
# But I assume you want to return the same type:
return self.__class__( value)
__rmul__ = __mul__

--
Steven D'Aprano

Apr 20 '07 #2
cf********@gmai l.com a écrit :
Sorry for the vague subject. Not sure what the right terminology is.

How can I use an instance's data by reference to the instance name,
not the instance attribute? OK the question is probably really poor
but hopefully an example will make it clear.

>>x=1
type(x)

<type 'int'>
>>x.__add__(1 )

2
>>print x

1
>>3*x

3

In this case x is an integer. My understanding is that x in an
instance of an integer class. Since it refers to only a single value
things like print x, 3*x etc operate on the instance name which seems
to refer to the instance data, not the instance itself. I want to do
the same for my own classes.
http://docs.python.org/ref/specialnames.html
Apr 21 '07 #3

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

Similar topics

10
1878
by: george young | last post by:
I had developed the habit of using the neat python form: if someinstance: someinstance.memb() because it seems cleaner than "if someinstance is not None". {please no flames about "is not None" vs. "!= None" ...} This seemed like a good idea at the time :(). Twice, recently, however, as my app grew, I thought, hmm... it would make things clearer if I gave
2
1306
by: paolo veronelli | last post by:
Writing software in Python for me it means work with dictionaries. They are next to humans head.They make no assumption on the names of variables ,mainly they leave the user to set his program with the names he like.They track me next to the user.......etc Not to bore I ask opinions abuot a very simple new class Rhash : The name to read as ErHash means recursive hash: Its implementation:
7
2297
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
13
1435
by: Bulba! | last post by:
Hello Mr Everyone, From: http://docs.python.org/tut/node11.html#SECTION0011900000000000000000 "Define a __iter__() method which returns an object with a next() method. If the class defines next(), then __iter__() can just return self:" The thing is, I tried to define __iter__() directly without explicit
1
2133
by: Steve Juranich | last post by:
I'm in the process of writing a few extension types, and there's one that I'd sort of like to have getitem, setitem, getslice, setslice functionality for. I've been looking through the docs and how things are done in Objects/listobject.c, and it appears tha there are a couple of ways to do it and I'd like to get some opinions on what's the best way. As I see it, here are my options (please correct me if I'm wrong):
3
5957
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,
6
1760
by: the.theorist | last post by:
I have a small, simple class which contains a dictionary (and some other stuff, not shown). I then have a container class (Big) that holds some instances of the simple class. When I try to edit the elements of the dictionary, all instances obtain those changes; I want each instance to hold separate entries. #----------Begin module test.py class ex: def __init__(self, val={}): self.value = val
14
4804
by: pat270881 | last post by:
hello, I have to implement a sequence class, however the header file is predefined class sequence { public: // TYPEDEFS and MEMBER CONSTANTS
1
3029
davydany
by: davydany | last post by:
Hey guys...a n00b Here for this site. I'm making a sequence class for my C++ class. And The thing is in the array that I have, lets say i put in {13,17,38,18}, when i see the current values for the array data from 0 to3, I get this {13, JUNK VALUE, 17,38, 18} and JUNK VALUE is like 1.8e831 or something like that. This happens when I use the attach() function and use the current() function to display the values at data I really want to...
0
9480
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,...
0
10313
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...
1
10081
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
8968
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...
0
6735
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();...
0
5378
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.