zoukankan      html  css  js  c++  java
  • python之元类

    python之元类

    1.类可以由默认的type来创建

    class People:
        def __init__(self,name):
            self.name = name
        def play(self,s):
            print(self.name,"在玩",s)
    
    p = People("xxx")
    p.play("yyy")
    // **********和下面等价***************
    def init(self,name):
        self.name = name
    def play(self, name):
        print(self.name,"在玩",name)
    People = type("People",(),{"name":"lqw","__init__":init,"play":play})
    // type 创建类  type("类名",(继承的类),{属性和方法,参照上方})
    p1 = People("xxx") 
    p1.play("y")
    

    2.类由metaclass元类来创建

    class Mytype(type):   # 原类
        _instance = None
        def __init__(self, class_name, super_name, name_space):  # 定制类的时候
            print("类名", class_name,"类型",type(class_name))
            print("继承类的名字", super_name,type(super_name))
            print("名称空间:", name_space,type(name_space))
            self._name = "lqw666"
        def __new__(cls, *args, **kwargs):   # 定制类
            print("cls是啥:", cls)
            print("args有啥:", args)
            print("kwargs有啥:", kwargs)
            print("我执行了?")
            print("*****************************************")
            s = super().__new__(cls, *args, **kwargs)
            return s
        def __call__(self, *args, **kwargs):    # 定制对象  下面是单例
            if not self._instance:
                self._instance = self.__new__(self,*args,**kwargs)
            self.__init__(self._instance,*args,**kwargs)
            return self._instance
    class People(object, metaclass=Mytype):
    
        def __init__(self,name):
            self.name = name
    
        def play(self, play):
            print(play, "被玩了")
    p = People("xxx")
    //	Peoples是原类的对象,也就是元类加()调用,先执行元类的__new__,在执行元类的__init__初始化People这个类,p是People的对象,就是People加(),对象加(),调用类的__call__,也就是调用元类的__call__,完成实例化对象
    
    元类可以定制类,下面几个小题目尝试一下
    1.类名必须大写,否则报错
    2.类有play方法,如果没有,给他添加一个
    3.类必须继承object,否则报错

    #####

    永远不要高估自己
  • 相关阅读:
    Annotation
    injector
    Java容器(container)
    build tool(构建工具)maven和gradle安装方法
    version control(版本控制)
    函数式编程
    URI与URL
    超文本传输协议HTTP
    annotation的理解
    Injection
  • 原文地址:https://www.cnblogs.com/liqiangwei/p/14684908.html
Copyright © 2011-2022 走看看