I've seen few questions with similar title but none of them seems suitable for me.
I'd like to create python objects, possibly with methods, on the fly with clean and "pythonic" syntax. What I have so far is:
import types
class QuickObject:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def with_methods(self, **kwargs):
for name, method in kwargs.items():
self.__dict__[name] = types.MethodType(method, self)
return self
Possible usages:
ob = QuickObject(x=10, y=20)
print(ob.x, ob.y)
ob = QuickObject(x=10, y=20).with_methods(sum=lambda s: s.x + s.y)
print(ob.x, ob.y, ob.sum())
It works and looks clear but seems a little bit bizarre and I believe there's a better way to achieve this than my definition of QuickObject class.
I am aware of namedtuple but it's immutable, does not go with methods and it's not that cool because it has to be defined beforehand for every object with different fields.
Built-in dictionaries also does not provide syntax for method calling nor let to access data with dictionary.key syntax without custom dict subclass.
TLDR: I am looking for a recipe for on-the-fly objects with:
- mutable fields,
- methods,
- nice
ClassName(field1=value, field2=value, ...)syntax.
Further reading:
types.MethodType. I am also curious if I'm not reinventing a wheel - maybe there's a more efficient way in a standard module or available in some third-party package.