473,386 Members | 1,698 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.

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,val):
self.val = val
y1 = y(10)
print y1
<__main__.y instance at 0x043C7B20>
3*y1
<type 'exceptions.TypeError'>: 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 1398
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,val):
self.val = val
>y1 = y(10)
print y1
<__main__.y instance at 0x043C7B20>
>3*y1
<type 'exceptions.TypeError'>: 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,val):
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********@gmail.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
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"...
2
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...
7
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...
13
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...
1
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...
3
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...
6
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...
14
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
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...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...
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.