Class subscripting

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Feb 17 20:22:11 EST 2006


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.




More information about the Python-list mailing list