Python中的metaclass, Python进阶必备?

  • 深入理解面向对象类的创建过程, 处理实际业务问题更加游刃有余

  • Python中的类也是对象, 通过type创建. type()是一个神奇的东西

  • 其实类的__init__和 __new__都是通过metaclass里指定的, 默认的metaclass为type, 当重写时继承时可以走自定义的Type类, 可以在类还没创建对象就执行一些操作, 用于一些复杂的业务场景, 提供了一种思路.

  • 通过在Type的__call__中的调用顺序执行new和init, new需要接受一个返回值, 就是创建出来的类

  • 可以通过type创建类和其属性

type("Foo", (object, ), {"flag":True, "run": lambda x : x **2 })
  • 从而引出 :
  • 能分析出这段代码的执行顺序吗, 为什么?
class MyType(type):
    def __init__(cls, *args, **kwargs):
        print("2. init")
        super().__init__(*args, **kwargs)

    def __new__(self, *args, **kwargs):
        print("1. new")
        return super().__new__(self, *args, **kwargs)

    def __call__(self, *args, **kwargs):
        print("3. call")
        self.__init__(self, *args, **kwargs)
        # print(self)
        object = self.__new__(self, *args, **kwargs)


class Foo(object, metaclass=MyType):
    def __new__(self, *args, **kwargs):
        print("3.1 Foo new")
    
    def __init__(self, *args, **kwargs):
        print("3.2 Foo init")

class Bar(Foo):
    def __init__(self):
        print("Bar init")
        super().__init__(self)


# obj = Foo()

Bar()
发布了140 篇原创文章 · 获赞 53 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44291044/article/details/104618299