Find static properties of a class in Python… here is a solution to the problem.
Find static properties of a class in Python
This is an unusual question, but I’d like to dynamically generate the __slots__
properties of the class based on any properties I happen to add to the class.
For example, if I have a class:
class A(object):
one = 1
two = 2
__slots__ = ['one', 'two']
I
want to do this dynamically instead of specifying the parameters manually, how do I do that?
Solution
When you tried to define slot , the class had not yet been built, so you could not define it dynamically from class A.
To get the desired behavior, use metaclasses to reflect on the definition of A and add slot properties.
class MakeSlots(type):
def __new__(cls, name, bases, attrs):
attrs['__slots__'] = attrs.keys()
return super(MakeSlots, cls).__new__(cls, name, bases, attrs)
class A(object):
one = 1
two = 2
__metaclass__ = MakeSlots