Use of __slots__

D

Don Taylor

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.
 
S

Steven D'Aprano

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"]

You define a RecordClass with a single slot, "foo".

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

Because you defined the class with only a slot for "foo", not "age".

Re-defining the __slots__ attribute at runtime does not add or subtract
slots from the class. It just breaks your class.

If you want to add and delete arbitrary attributes at runtime, don't use
slots.
 
C

Crutcher

Steven is right, however, there is a way:

def new_record(slotlist):
class R(object):
__slots__ = slotlist
return R()

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top