Creating attributes on classes
Programmatic addition of methods.
I've gotten used to manipulating members of Python objects with getattr, setattr etc. But a recent similar problem had me stumped. I had a class that I wanted to create a large number of similar behaving properties on (they would all manipulate an internal dictionary):
>>> f = Foo() >>> f.contributor = 'xyz' >>> f.contributor 'xyz' >>> del f.contributor
Repeat for fourteen other properties. Rather than write more than 30 near-identical methods, there should be some way to define the class by looping over the field names. The temptation is to do it inside the class, but this runs into several problems:
- fields = [ 'contributor', 'coverage', 'creator', 'data',
- 'description', 'format', 'identifier', 'language', 'publisher', 'relation', 'rights', 'source', 'subject', 'title', 'type' ]
- class Foo(object):
- for f in fields: # how do I name the property f = property (...) # what do I setattr on? the class isn't defined yet ... setattr (Foo, f, property (...))
The proper and obvious solution is to add properties to the class after it has been created:
class Foo (object): pass for f in fields: setattr (Foo, f, property (...))