python - python 如何确定合适的元类?

标签 python grammar cpython

我也许可以在 official doc 中找到答案,但我还是无法得到它。对于第二个和第三个案例,您能给我更详细或更直接的解释吗?如果您能给我一些例子,我将不胜感激!

The appropriate metaclass for a class definition is determined as follows:

  • if no bases and no explicit metaclass are given, then type() is used;
  • if an explicit metaclass is given and it is not an instance of type(), then it is used directly as the metaclass;
  • if an instance of type() is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used.

最佳答案

假设您尝试通过元类(在本例中是两个元类)实现 Singleton 模式。

class Singleton(type):
    _inst = {}

    def __call__(cls, *args, **kwargs):
        return cls._inst.setdefault(cls, super().__call__(*args, **kwargs))

class Singleton2(Singleton):
    def __call__(cls, *args, **kwargs):
        return super().__call__(*args, **kwargs)



class SingletonClass1(metaclass=Singleton):
    pass


class SingletonClass2(SingletonClass1, metaclass=Singleton2):
    pass


class SingletonClass3():
    pass


class SingletonClass4(SingletonClass2, metaclass=Singleton):
    pass

type(class_obj)函数返回 class_obj 的元类.

这是您的案例:

  1. 如果没有给出基类和显式元类,则使用 type();

    type(SingletonClass3) --> <class 'type'>

2. 如果给出了显式元类并且它不是 type() 的实例,则直接将其用作元类;

`type(SingletonClass2) --> <class '__main__.Singleton2'>`

3. 如果 type() 的实例作为显式元类给出,或者定义了基类,则使用最派生的元类;

`type(SingletonClass4) --> <class '__main__.Singleton2'>`

如果你从SingletonClass1继承了SingletonClass2,但忘记从Singleton继承Singleton2,就会导致TypeError。

The most derived metaclass is one which is a subtype of all of these candidate metaclasses. If none of the candidate metaclasses meets that criterion, then the class definition will fail with TypeError.

更新: 元类可以是函数,但不是 type 的实例,因此第二种情况(如果给出了显式元类并且它不是类型的实例)可以与此相关。这是元类函数的单例实现。

def singleton_func(class_name, bases, attrs):
    _inst = {}

    def custom_new(cls):
        return _inst.setdefault(cls, object.__new__(cls))

    attrs['__new__'] = custom_new
    return type(class_name, bases, attrs)


class SingletonClass5(metaclass=singleton_func):
    pass

关于python - python 如何确定合适的元类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284561/

相关文章:

python - python - 如何按两列或多列对python pandas中的dataFrame进行排序?

objective-c - Objective-C 中的保留关键字?

python - 使用具有不同项目大小的 Py_buffer 和 PyMemoryView_FromBuffer

python - 如何从一组数据点插入单个 ("non-piecewise") 三次样条?

python - 转换时间字符串并将其插入时间字段 django 的有效方法

android - 将 grep 与 python subprocess.check_output 和 adb logcat 结合使用

java - 如何解析这个语法?

grammar - 使用一元 + 和 - 的算术表达式的明确语法

python - 为什么使用切片复制列表[:] faster than using the obvious way?

python - 为什么集合减法和 .difference() 运行速度不同