Metaclass不会初始化新类

时间:2018-06-12 20:05:23

标签: python-3.x metaclass

一切!我的代码存在很大问题。我尝试编写简单的代码作为理解元编程的简单框架。我有下一个问题。

doc1 = Document()
doc1.id = 20
doc2 = Document()
print (doc2.id) # show 20, but it's wrong!!! It should be 0

这是我的代码清单

class BaseModel(type):
def __new__(cls, name, bases, attrs,  **kwargs):
    instance = super().__new__

    parents = [b for b in bases if isinstance(b, BaseModel)]
    if not parents:
        return instance(cls, name, bases, attrs)

    module_ = attrs.pop('__module__')
    attrs_ = {'__module__': module_}

    classcell_ = attrs.pop('__classcell__', None)
    if classcell_ is not None:
        attrs_['__classcell__'] = classcell_

    for key, value in attrs.items():
        if not isinstance(value, Field):
            continue

        print (value.__dict__)
        attrs_[key] = value

    instance = instance(cls, name, bases, attrs_, **kwargs)

    return instance


class Model(metaclass=BaseModel):
    pass

class Field:
    def __init__(self, value=0):
        self._value = value

    def __get__(self, instance, owner):
        return self._value

    def __set__(self, instance, value):
        self._value = value

class Document(Model):
    id = Field()

发生了什么?我认为主要问题是元类中的 new 方法。我对吗?如何解决?

1 个答案:

答案 0 :(得分:2)

您尝试使用您的元类实现的目标令人困惑,尽管它不是问题的根源。实现唯一ID不需要元类,它只需要精心设计的描述符。

在您的情况下,您的Field描述符会跟踪单个值,而不是现有的实例和ID对。

要解决此问题,您需要保留已经采用的值的弱引用。

import weakref, itertools

class UniqueId:
    def __init__(self):
        self._values = weakref.WeakKeyDictionary()

    def __get__(self, instance, owner):
        if instance is None:
            return self
        else:
            return self._values[instance]

    def __set__(self, instance, value):
        if value not in self._values.values():
            self._values[instance] = value
        else:
            raise ValueError('Unique id {} already taken'.format(value))

    def get_unique_id(self):
        existing_ids = set(self._values.values())
        return next(i for i in itertools.count() if i not in existing_ids)

class Model:
    def __new__(cls, *args, **kwargs):
        instance = super().__new__(cls, *args, **kwargs)

        for name, attr in cls.__dict__.items():
            if isinstance(attr, UniqueId):
                setattr(instance, name, attr.get_unique_id())

        return instance

class Document(Model):
    id = UniqueId()

实施例

doc1 = Document()
print(doc1.id) # 0

doc2= Document()
print(doc2.id) # 1

doc2.id = 0 # ValueError: Unique id 0 already taken