I'm trying to create metaclass in Python (2.7) that will set arguments passed to object's __init__ as object attributes.
class AttributeInitType(type):
def __call__(self, *args, **kwargs):
obj = super(AttributeInitType, self).__call__(*args, **kwargs)
for k, v in kwargs.items():
setattr(obj, k, v)
return obj
Usage:
class Human(object):
__metaclass__ = AttributeInitType
def __init__(self, height=160, age=0, eyes="brown", sex="male"):
pass
man = Human()
Question: I want man instance to have defaults attributes set as in class's __init__. How can I do it?
Update: I've came to even better solution that:
- inspects
__init__method only once during class creation - does not override attributes that where (possibly) set by class's real
__init__
Here is the code:
import inspect
import copy
class AttributeInitType(type):
"""Converts keyword attributes of the init to object attributes"""
def __new__(mcs, name, bases, d):
# Cache __init__ defaults on a class-level
argspec = inspect.getargspec(d["__init__"])
init_defaults = dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
cls = super(AttributeInitType, mcs).__new__(mcs, name, bases, d)
cls.__init_defaults = init_defaults
return cls
def __call__(mcs, *args, **kwargs):
obj = super(AttributeInitType, mcs).__call__(*args, **kwargs)
the_kwargs = copy.copy(obj.__class__.__init_defaults)
the_kwargs.update(kwargs)
for k, v in the_kwargs.items():
# Don't override attributes set by real __init__
if not hasattr(obj, k):
setattr(obj, k, v)
return obj