Use of __slots__

Don Taylor nospamformeSVP at gmail.com
Sun Feb 26 17:01:45 EST 2006


Hi:

I am puzzled about the following piece of code which attempts to create 
a class that can be used as record or struct with a limited set of 
allowed attributes that can be set into an instance of the class.

class RecordClass(object):
     __slots__ = ["foo"]
     def __init__(self, args):
         print "Initial slots = ", RecordClass.__slots__
         RecordClass.__slots__ = list(args)
         print "Final slots = ", RecordClass.__slots__
     pass

def new_record(slotlist):
     return RecordClass(slotlist)

if __name__ == "__main__":
      record1 = new_record(["age", "name", "job"])
      record1.age = 27
      record1.name = 'Fred'
      record1.job = 'Plumber'
      record1.salary = 50000

When executed I get:

Initial slots =  ['foo']
Final slots =  ['age', 'name', 'job']
Traceback (most recent call last):
   File "D:\ProgrammingProjects\JustForTesting\recordclasses.py", line 
37, in ?
     record1.age = 27
AttributeError: 'RecordClass' object has no attribute 'age'

I don't understand why I cannot set an attribute 'age' into record1.

Thanks,

Don.




More information about the Python-list mailing list