LUIInitialState.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. __all__ = ["LUIInitialState"]
  2. class LUIInitialState:
  3. """ Small helper class to pass keyword arguments to the LUI-objects. It takes
  4. all keyword arguments of a given call, and calls obj.<kwarg> = <value> for
  5. each keyword. It usually is called at the end of the __init__ method. """
  6. def __init__(self):
  7. raise Exception("LUIInitialState is a static class")
  8. # Some properties have alternative names, under which they can be accessed.
  9. __MAPPINGS = {
  10. "x": "left",
  11. "y": "top",
  12. "w": "width",
  13. "h": "height"
  14. }
  15. @classmethod
  16. def init(cls, obj, kwargs):
  17. """ Applies all keyword arguments as properties. For example, passing
  18. dict({"left": 10, "top": 3, "color": (0.2, 0.6, 1.0)}) results in
  19. behaviour similar to:
  20. element.left = 10
  21. element.top = 3
  22. element.color = 0.2, 0.6, 1.0
  23. Calling this method allows setting arbitrary properties in
  24. constructors, without having to specify each possible keyword argument.
  25. """
  26. for arg_name, arg_val in kwargs.items():
  27. arg_name = cls.__MAPPINGS.get(arg_name, arg_name)
  28. if hasattr(obj, arg_name):
  29. setattr(obj, arg_name, arg_val)
  30. else:
  31. raise AttributeError("{0} has no attribute {1}".format(
  32. obj.__class__.__name__, arg_name))