简体   繁体   English

元类和__slots__?

[英]Metaclasses and __slots__?

So, I am reading a bit about metaclasses in Python, and how type() 's three-argument alter-ego is used to dynamically create classes. 所以,我正在阅读Python中的元类,以及如何使用type()的三参数alter-ego来动态创建类。 However, the third argument is usually a dict that initializes the to-be created class' __dict__ variable. 但是,第三个参数通常是一个初始化要创建的类' __dict__变量的dict

If I want to dynamically create classes based on a metaclass that uses __slots__ instead of __dict__ , how might I do this? 如果我想基于使用__slots__而不是__dict__的元类动态创建类,我该怎么做? Is type() still used in some fashion along with overriding __new__() ? 是否仍然以某种方式使用type()以及重写__new__()

As an FYI, I am aware of the proper uses for __slots__ , to save memory when creating large numbers of a class versus abusing it to enforce a form of type-safety. 作为一个FYI,我知道__slots__的正确用法,在创建大量类时节省内存而不是滥用它来强制执行类型安全的形式。


Example of a normal (new-style) class that sets __metaclass__ and uses a __dict__ : 设置__metaclass__并使用__dict__的普通(新式)类的__metaclass__

class Meta(type):
    def __new__(cls, name, bases, dctn):
        # Do something unique ...
        return type.__new__(cls, name, bases, dctn)

class Foo(object):
    __metaclass__ = Meta

    def __init__(self):
        pass


In the above, type.__new__() is called and the fourth argument (which becomes the third when actually used) creates a __dict__ in Foo . 在上面,调用type.__new__() ,第四个参数(在实际使用时成为第三个参数)在Foo创建__dict__ But if I wanted to modify Meta to include __slots__ , then I have no dictionary to pass on to type() 's __new__() function (as far as I know -- I haven't tested any of this yet, just pondering and trying to find some kind of a use-case scenario). 但是如果我想修改Meta以包含__slots__ ,那么我没有字典可以传递给type()__new__()函数(据我所知 - 我还没有测试过任何这个,只是思考和试图找到某种用例场景)。

Edit: A quick, but untested guess, is to take a dict of the values to be put into the __slots__ variables and pass it to type.__new__() . 编辑:一个快速但未经测试的猜测是将值放入__slots__变量并将其传递给type.__new__() Then add an __init__() to Meta that populates the __slots__ variables from the dict. 然后将__init__()添加到Meta ,从而填充dict中的__slots__变量。 Although, I am not certain how that dict would reach __init__() , because the declaration of __slots__ prevents __dict__ from being created unless __dict__ is defined in __slots__ ... 虽然,我不确定该dict将如何到达__init__() ,因为__slots__的声明会阻止创建__dict__ ,除非在__slots__定义了__dict__ ...

You can't create a type with a non-empty __slots__ attribute. 您无法创建具有非空__slots__属性的类型。 What you can do is insert a __slots__ attribute into the new class's dict, like this: 你可以做的是在新类的dict中插入__slots__属性,如下所示:

class Meta(type): 
    def __new__(cls, name, bases, dctn):
         dctn['__slots__'] = ( 'x', )
         return type.__new__(cls, name, bases, dctn)

 class Foo(object):
    __metaclass__ = Meta

    def __init__(self):
        pass 

Now Foo has slotted attributes: 现在Foo有一些插槽属性:

foo = Foo() 
foo.y = 1

throws

 AttributeError: 'Foo' object has no attribute 'y'

dctn in your example of a metaclass is the class dictionary, not the instance dictionary. 您的元类示例中的dctn字典,而不是实例字典。 __slots__ replaces the instance dictionary. __slots__替换实例字典。 If you create two examples: 如果您创建两个示例:

class Meta(type):
    def __new__(cls, name, bases, dctn):
        return type.__new__(cls, name, bases, dctn)

class Foo1(object):
    __metaclass__ = Meta

class Foo2(object):
    __metaclass__ = Meta
    __slots__ = ['a', 'b']

Then: 然后:

>>> f1 = Foo1()
>>> f2 = Foo2()
>>> f1.__dict__ is Foo1.__dict__
False
>>> f2.__dict__
Traceback (most recent call last):
    ...
AttributeError: 'Foo2' object has no attribute '__dict__'

More about slots defined in metaclasses. 有关在元类中定义的槽的更多信息。

if type 's subclass defines non-empty __slots__ , Python throws a TypeError because of some complicated implementation-related stuff . 如果type的子类定义非空的__slots__ ,Python会因为某些复杂的实现相关内容而抛出TypeError

In [1]:

class Meta(type):
    __slots__ = ('x')

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-1b16edef8eca> in <module>()
----> 1 class Meta(type):
      2     __slots__ = ('x')

TypeError: nonempty __slots__ not supported for subtype of 'type'

Empty __slots__ on the other hand don't produce any errors, but seam to have no effect. 另一方面,空__slots__不会产生任何错误,但接缝无效。

In [2]:

class Meta(type):
    __slots__ = ()

class Foo(metaclass=Meta):
    pass

type(Foo)

Out [2]:

__main__.Meta

In [3]:

Foo.y = 42
Foo.y

Out [3]:

42

In [4]:

Foo.__dict__

Out [4]:

mappingproxy({'y': 42, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__'})

In [5]:

foo = Meta('foo', (), {})
type(foo).__slots__

Out [5]:

()

In [6]:

foo.x = 42
foo.x

Out [6]:

42

In [7]:

foo.__dict__

Out [7]:

mappingproxy({'__dict__': <attribute '__dict__' of 'foo' objects>, 'x': 42, '__module__': '__main__', '__doc__': None, '__weakref__': <attribute '__weakref__' of 'foo' objects>})

In [8]:

# Testing on non-metaclasses. Just in case.
class Bar:
    __slots__ = ()

b = Bar()
b.__dict__

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-54-843730c66f3f> in <module>()
      3 
      4 b = Bar()
----> 5 b.__dict__

AttributeError: 'Bar' object has no attribute '__dict__'

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

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