Newbie: How to touch "global" variables

John Hunter jdhunter at ace.bsd.uchicago.edu
Tue Jul 30 14:18:51 EDT 2002


>>>>> "Jeff" == Jeff Layton <jeffrey.b.layton at lmco.com> writes:

    Jeff> modules. Unfortunately, I don't know the variable names
    Jeff> ahead of time, so I think having the ability to "add" them
    Jeff> to an instance is where I'm header
    Jeff> (e.g. MyShare.variable=value). Then I can "quizz" the
    Jeff> instance looking for specific variables (using dir() ). I
    Jeff> don't think at this point I need to change any of the values
    Jeff> in the instance, but I may want to do that at some point (at
    Jeff> least for the sake of learning out to do it).  Thanks again
    Jeff> for your help and explanation.

If you want to work with attributes where you don't know the names,
you'll want to familiarize yourself with the built-in functions
hasattr, setattr, and getattr

class X:
  def __init__(self):
    self.a = 1

x = X()

if hasattr(x, 'a'):
  a = getattr(x, 'a')

#b = getattr(x, 'b')  # raises AttributeError exception

setattr(x, 'b', 12)  # same as x.b = 12
b = getattr(x, 'b')  # now ok
b = x.b              # also ok

# Classes store all of their data attributes in a dictionary called
# __dict__.  So you can also manipulate attributes with all the
# dictionary methods (has_key, get, setdefault, ...)
# get returns the value of c or 123 if c is not a key
c = x.__dict__.get('c', 123)  #c is 123
x.c = 100
c = x.__dict__.get('c', 123)  #c is 100

That's why the Borg pattern works, because at class initialization,
the instance dictionary is set to be equal to self.__shared_state,
which is a class attribute. 

All of attr methods call special class methods by the same name with
the leading and trailing __.  So you can control what happens with
setattr for example, restricting it to a certain set of keys, or
enfocing a certain naming convention on keys (like lower case only or
whatever)

Here is an example that raises an exception if the user tries to use a
short key.  No reason for it, just an example...

class X:
    a = 1
    def __setattr__(self, key, val):
        if len(key)<4:
            raise ValueError, 'No short keys!'
        self.__dict__[key] = val


x = X()

x.first = 'John'
x.last = 'Hunter'
x.age = 33   #raises an exception here

You can do a lot with the special methods of python, and there are a
lot of them

See 
http://python.org/doc/current/ref/specialnames.html
http://diveintopython.org/fileinfo_specialmethods.html
http://diveintopython.org/fileinfo_morespecial.html

John Hunter




More information about the Python-list mailing list