使用元类添加静态方法

时间:2017-03-29 13:20:48

标签: python static-methods metaclass

由于元类,我希望将静态方法添加到类中。这可能吗?这是我试过的:

from django.conf import settings
import six

class Setting(object):
    def __init__(self, name=None, default=None):
        self.name = name
        self.default = default


class Metaclass(type):
    def __new__(mcs, cls, bases, dct):
        new_attr = {}
        for name, val in dct.items():
            if isinstance(val, Setting):
                # populate name
                if val.name is None:
                    val.name = name.upper()
                # add a static getter
                new_attr['get_%s' % name] = staticmethod(lambda: getattr(
                    django_settings, val.name, val.default))
            new_attr[name] = val

        return super(Metaclass, mcs).__new__(mcs, cls, bases, new_attr)


class AppSettings(six.with_metaclass(Metaclass)):
    pass

我还尝试在创建类之后推迟静态getter的赋值,例如:

new_class = super(Metaclass, mcs).__new__(mcs, cls, bases, {})
# loop on dct, memorize what methods to set
for name, method in deferred_methods.items():
    setattr(new_class, name, method)
return new_class

它似乎正在工作,但是当我使用AppSettings的子类和其中的一些设置运行一些测试时,一切都混淆了。每次重新运行测试时,行为都会发生变化。这是由于使用了lambdas?

0 个答案:

没有答案