creating class properties dynamically
The three-argument for of type
lets you create classes dynamically. So, a sketch:
def dynamic_getter(self):
# acquire "stuff"
return stuff
def dynamic_setter(self,stuff):
# store "stuff"
pass
DynamicClass = type('DynamicClass', (SomeBase,), {"dynamic_property_name":property(fget=dynamic_getter,fset=dynamic_setter)})
Or, more concretely:
In [1]: class SomeBase:
...: def __init__(self):
...: self._foo = 42
...:
...: def dynamic_getter(self):
...: # acquire "stuff"
...: return self._foo
...:
...: def dynamic_setter(self,stuff):
...: # store "stuff"
...: pass
...:
...: DynamicClass = type('DynamicClass', (SomeBase,), {"dynamic_property_name":property(fget=dynamic_getter,fset=dynamic_setter)})
In [2]: instance = DynamicClass()
In [3]: instance.dynamic_property_name
Out[3]: 42
Note: type
is literally a class object like any other, and calling it in it's three-argument form is a constructor for new class object instances, it is the class that creates other class objects, i.e. a metaclass. Indeed, you can think of a class definition statement as syntactic sugar for the above.
A template-based with exec
(if you want to use a complex statement, you'd need exec
, eval
only allows expressions) approach is also viable, if you find that easier to work with. Indeed, that is how collections.namedtuple
works in the standard library.
Note: you seem to be confused about the nature of properties in Python. Instance attribtus are not specified on the class, rather, you'd add a function that initializes those instance attributes (typically __init__
) but you can add instance attributes anywhere, even outside of a method/class.