Setting a class attribute given its name

Miki Tebeka tebeka at cs.bgu.ac.il
Thu Jun 19 07:45:50 EDT 2003


Hello Edward,

> class X(object):
>      i = 1
> 
> Given the string 'i', how do I set the class attribute? The following 
> doesn't work (Python 2.2.3):
> 
> class X(object):
>      setattr(X, 'i', 1)
You can make a function that creates this class:
'''defstruct - Somewhat like lisps
'''

from types import StringType

def defstruct(*slots):
    '''Define a new structure.
    Person = defstruct('name', 'id')
    me = Person('miki', 0)
    me.name
    '''
    # Slots must be strings
    for slot in slots:
        if type(slot) != StringType:
            raise ValueError('Slots must be strings [%s is not]' % slot)
    # Create the new class
    class st:
        def __init__(self, **kw):
            # Check keywords
            for slot in kw.keys():
                if slot not in slots:
                    raise ValueError('%s is not a valid slot' % slot)
            # Assign values (default to None)
            for slot in slots:
                if kw.has_key(slot):
                    self.__dict__[slot] = kw[slot]
                else:
                    self.__dict__[slot] = None
    return st

HTH.
Miki




More information about the Python-list mailing list