我正在尝试在 Python(2.7)中创建元类,该类将设置传递给对象__init__的参数作为对象属性.
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
用法:
class Human(object):
__metaclass__ = AttributeInitType
def __init__(self, height=160, age=0, eyes="brown", sex="male"):
pass
man = Human()
问题:我希望人实例具有在类的__init__中设置的默认属性.我该怎么做?
更新:我已经找到了更好的解决方案:
>在类创建期间仅检查__init__方法一次
>不会覆盖(可能)由类的实际__init__设置的属性
这是代码:
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