formations/python-avancé/examples/metaclass-autoinit.py

28 lines
760 B
Python

class AutoInit(type):
def __new__(mcs, name, bases, ns, **kwargs):
cls = type.__new__(mcs, name, bases, ns)
cls._attributes = kwargs["attributes"]
return cls
def __call__(self, *args, **kwargs):
attributes = {}
for name in self._attributes:
attributes[name] = kwargs.pop(name, None)
obj = super().__call__(*args, **kwargs)
for key, value in attributes.items():
setattr(obj, key, value)
return obj
class Point(metaclass=AutoInit, attributes=("x", "y", "z")):
...
origin = Point(x=0, y=0, z=0)
print(origin.x, origin.y, origin.z) # 0 0 0
NonePoint = Point()
print(NonePoint.x, NonePoint.y) # None None
# origin = Point(x=0, y=0, blah=42) # TypeError !