JAVA网络爬虫
HttpClient

导航

 

python元类

  • 动态创建类

    def test(name):
        if name == "Foo":
            class Foo(object):
                pass
            return Foo    #反回的是类,不是类的实列
        else:
             class Bar(object):
                 pass
             return Bar
    
    My_class = test("Foo")
    print(My_class)  #函数反回的是类,不是类的实列
    
    print(My_class()) #你可以通过类,创建实列,也就是对象
    
    # 运行结果
    <class '__main__.test.<locals>.Foo'>
    <__main__.test.<locals>.Foo object at 0x101a14550>
    
  • 元类-1

    #实列对象是类创建出来的 类是  元类创建出来的
    #元类就是type
    
    #type(类型名,由父类名称组成的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))
    
    Test = type("Test",(),{})#这就是元类
    my_type = type(Test)
    print(my_type)
    t = Test()
    t.name = "asd"
    my_t = type(t)
    print(my_t)
    
    print("="*50)
    
    #给类添加属性和方法
    def printNum(self):
        print("%s"%self.name)
    
    Test2 = type("Test2",(),{"name":"laowang","printNum":printNum}) #这个printNum是函数的引用
    t2 = Test2()
    t2.printNum()
    
    print("="*50)
    
    #继承
    class Animal:
        def eat(self):
            print("----吃----")
    
    
    class Dog(Animal):
        pass
    
    Cat = type("Cat",(Animal,),{})  # type元类  创建了一个类   Cat指向了那个类
    cat = Cat()
    cat.eat()
    
    
    
    print("="*50)
    
    
    
    
    #type创建等价于class定义  但是type是动态的
        
    class Person:
        pass
    
    print(type(Person))
    
    # 运行结果
    <class 'type'>
    <class '__main__.Test'>
    ==================================================
    laowang
    ==================================================
    --------
    ==================================================
    <class 'type'>
    
  • 元类-2-控制类的创建

    def upper_attr(future_class_name,future_class_parents,future_class_attr): #这里属性当字典接收
    
        #遍历属性字典,把不是__开头的属性名字变为大写
    
        newAttr = {}
    
        for key,value in future_class_attr.items():  #遍历字典
            if not key.startswith("__"): #不是以__开头的属性名
                newAttr[key.upper()] = value #把他转换成大写的名字 在把值复制给这个属性
    
                return type(future_class_name,future_class_parents,newAttr)  #在用type创建一个类  反回给下面的类而
                                                                             #Foo指向了这个类
    
                    #metaclass = upper_attr 是告诉python解释器 这个类按照上面的函数创建
    
    class Foo(object,metaclass=upper_attr):  #把类的名字和父类和属性传递给了upper_atter这个函数
        bar = 'bip'
    
    print(hasattr(Foo,'bar')) #测试这个类有没有这个属性  右就True 没有就False+
    print(hasattr(Foo,'BAR'))
    f = Foo()
    print(f.BAR)
    
    # 运行结果
    False
    True
    bip
    
posted on 2019-08-27 19:46  gmlgxx  阅读(59)  评论(0)    收藏  举报