简体   繁体   English

如何在 Python 中初始化类(不是实例)?

[英]How to initialize classes (not instances) in Python?

I want to merge constraints from the current and inherited classes only once a class is loaded (not per object.).我只想在加载 class 后合并来自当前类和继承类的约束(不是每个 object。)。

class Domain(Validatable):

    constraints = {...}

To do this I defined a method _initialize_class_not_instance that should be called once for each class:为此,我定义了一个方法_initialize_class_not_instance ,应该为每个 class 调用一次:

class Validatable:

    @classmethod
    def _initialize_class_not_instance(cls):
        # merge constraints from derived class and base classes
        pass

    __class__._initialize_class_not_instance() # doesn't work
    # Validatable._merge_constraints() # doesn't work too

The problem is that __class__ doesn't exist in this context and Validatable is not defined too.问题是__class__在这种情况下不存在并且Validatable也没有定义。 But I want to avoid, that the user of my API has to call the initialize method explicitely or has to use an additional class decorator.但我想避免,我的 API 的用户必须显式调用初始化方法或必须使用额外的 class 装饰器。

Any ideas how to initialize the class?任何想法如何初始化 class?

Use a metaclass.使用元类。

class MetaClass(type):
  def __init__(cls, name, bases, d):
    type.__init__(cls, name, bases, d)
    cls.foo = 42

class MyClass(object):
  __metaclass__ = MetaClass

print MyClass.foo

I ended up with a class decorator and without inheritance.我最终得到了一个 class 装饰器,没有 inheritance。 This decorator merges the constraints of the current and inherited classes and overrides the __init__ method:这个装饰器合并了当前类和继承类的约束并覆盖了__init__方法:

def validatable(cls):

    # merge constraints from derived class and base classes here ...

    original_init = cls.__init__
    def init_to_insert(self, *args, **keywords):
        self.errors = {}
        original_init(self, *args, **keywords)   
    cls.__init__ = init_to_insert
    return cls

This is the key for my solution, since the decorator has to modify the class (merging constraints and inserting methods) and instances.这是我的解决方案的关键,因为装饰器必须修改 class(合并约束和插入方法)和实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM