473,386 Members | 1,795 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 subscripting

Assume we have a class Foo, and instance called bar.

a variable called baz1 has the value 3.0, baz2 is uninitialized

Is there a way of reflecting the variable with such syntax:

print bar[<var_index>], where var_index is a number representing
internal index.

bar[<var_index>] = 4.2. #Setting baz2 to 4.2

Thanks and regards,

Ronny Mandal
Feb 18 '06 #1
4 1250
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ronny Mandal wrote:
Assume we have a class Foo, and instance called bar.

a variable called baz1 has the value 3.0, baz2 is uninitialized

Is there a way of reflecting the variable with such syntax:

print bar[<var_index>], where var_index is a number representing
internal index.

bar[<var_index>] = 4.2. #Setting baz2 to 4.2


Hmmm... I don't like this much, though it'd could be a little better if
you kept a separate list which you update in __setitem__ instead of
constructing a new list for each __getitem__ call.

I'm sure someone has a more elegant solution, I'm afraid I'm too tired
to come up with anything better.

Oh, and don't forget to check that key is an IntType!

class MyClass:

def __init__(self):

self.a = "I'm a!"
self.b = "I'm b!"

def __getitem__(self, key):

if key != None:

return list(self.__dict__.values())[key]

x = MyClass()
print x[0]
print x[1]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFD9msAefZ4eWAXRGIRAjN0AJ40pfI5fhm2WK7gV1Q4dE r9Nv10TgCgo6mY
ovWBqjXvdSjH3zNh61j5qj4=
=XrYe
-----END PGP SIGNATURE-----
Feb 18 '06 #2
Ronny Mandal wrote:
Assume we have a class Foo, and instance called bar.

a variable called baz1 has the value 3.0, baz2 is uninitialized

Is there a way of reflecting the variable with such syntax:

print bar[<var_index>], where var_index is a number representing
internal index.

bar[<var_index>] = 4.2. #Setting baz2 to 4.2

Thanks and regards,

Ronny Mandal


I can't figure out why did you tell us that baz1 has value of
3.0? What does that have to do with anything? It is also
uncloear how you think that setting something inside bar
class instance could possibly create a variable called
baz2? Python doesn't have a concept of "unitialized" variables.
Before they are initialized they simply don't exist. Variables
in Python aren't buckets, variables are pointers to information.
I think we need more information about what you are trying to
accomplish before we can help.

Just as a wild guess I think you want a dictionary.

vdict=['baz1': 3.0, 'baz2': None}

vdict['baz2']=4.2

print vdict['baz2']

if you insist on an index you can do:

vars=['baz1','baz2']

print vdict[vars[2]]

I'm REALLY guessing here, so I don't know if I'm helping.

-Larry Bates
Feb 18 '06 #3

Ronny> Assume we have a class Foo, and instance called bar. a variable
Ronny> called baz1 has the value 3.0, baz2 is uninitialized

Ronny> Is there a way of reflecting the variable with such syntax:

Ronny> print bar[<var_index>], where var_index is a number representing
Ronny> internal index.

Ronny> bar[<var_index>] = 4.2. #Setting baz2 to 4.2

Sure. Check out the special method names for container types:

http://www.python.org/dev/doc/devel/...nce-types.html

To index into instances of your class you need to define a __getitem__
method.

Skip

Feb 18 '06 #4
On Sat, 18 Feb 2006 01:09:22 +0100, Ronny Mandal wrote:
Assume we have a class Foo, and instance called bar.

a variable called baz1 has the value 3.0, baz2 is uninitialized
Python doesn't have variables. It has names which are bound to objects. Do
you mean that the name baz1 is bound to the value 3.0?

Because Python has no variables, you can't have uninitialized variables.
You can have names which are bound to values (objects), and you can have
names which don't exist yet. Do you mean that baz2 is a name which doesn't
yet exist?

In other words, just so we are clear, at this point we have the following
Python code:
class Foo:
pass

bar = Foo()
baz1 = 3.0
# baz2 not yet used.
Is there a way of reflecting the variable with such syntax:

print bar[<var_index>], where var_index is a number representing
internal index.

bar[<var_index>] = 4.2. #Setting baz2 to 4.2

No. But you can do better:

baz = {} # holder for the values of the bazmatron.
baz[1] = 3.0
baz[2] = 4.2
baz[25] = 3.9

# Check if we have the third value for the bazmatron.

if baz.has_key(3): # "Look before you leap"
print baz[3]

# Another way to do the same thing.
try:
print baz[3]
except KeyError:
print "No third value. Initializing it now."
baz[3] = 0.0

# A third way.
print baz.get(3, 0) # Prints 0 if no third value exists.

# A fourth way: print baz[3] with a default value of 0,
# and set the value if it doesn't already exist.
print baz.setdefault(3, 0)

--
Steven.

Feb 18 '06 #5

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

Similar topics

2
by: Fernando Rodriguez | last post by:
Hi, I need to traverse the methods defined in a class and its superclasses. This is the code I'm using: # An instance of class B should be able to check all the methods defined in B #and A,...
1
by: Oplec | last post by:
Hi, I'm learning C++ as a hobby using The C++ Programming Language : Special Edition by Bjarne Stroustrup. I'm working on chpater 13 exercises that deal with templates. Exercise 13.9 asks for me...
4
by: Matt Garman | last post by:
Is there any difference, performance-wise, accessing elements of a vector using iterators or the subscript operator? In other words, say I have a vector of strings: vector<string> strvec; ...
28
by: Steven T. Hatton | last post by:
This may be another question having an obvious answer, but I'm not seeing it. I'm trying to create a class that derives from std::valarray<std::string>. I don't need a template, and I haven't come...
9
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class...
12
by: James Brown | last post by:
Hi all, Having problems designing a template-class. I'll describe my scenario first then show what I've come up with so far: Need a class to provide pointer/array-like access to an area of...
9
by: buda | last post by:
Hi, I've been wondering for a while now (and always forgot to ask :) what is the exact quote from the Standard that forbids the use of (&array) (when x >= number_of_columns) as stated in the FAQ...
7
by: Netocrat | last post by:
The code at the bottom illustrates the nature of a situation discussed on comp.lang.asm.x86. Basically an unsigned integer is being used as a negative index in a loop, and it works as though the...
5
by: arnuld | last post by:
i have solved the problem. any comments on it: /* C++ Primer 4/e * chapter 3 * * exercise 3.24 * STATEMENT: * consider the sequence 1,2,3,5,13,21. Initialize a "bitset<32>" object that...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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.