zoukankan      html  css  js  c++  java
  • python元类:type和metaclass

    python元类:type和metaclass

    • python中一切皆对象,所以类本身也是对象。类有创建对象的能力,那谁来创建类的呢?答案是type。

    1.用tpye函数创建一个类

    class A(object):
        pass
    
    # 类名 = tpye(类名-str,父类-tuple,属性-dict)
    #此条命令创建类相当于上个class创建类,效果是一样的。
    B = type('B', (object,), {})
    
    print(A)
    print(B)
    
    

    输出结果:

    <class '__main__.A'>
    <class '__main__.B'>
    
    • 有没有发现输出的结果是一样的。type创建出来的和class定义的都是类。

    2.定义带有属性的类:

    >>> class Foo(object):
    …       bar = True
    
    #相当于:
    >>> Foo = type("Foo", (object), {'bar':True})
    
    

    3.定义带有方法的类:

    class Dog(object):
        def bark(self):
            print('wang wang ..')
    
        @classmethod
        def eat(self):
            print('i am eating...')
    
    # ----------------------------
    # 上面创建的类可以用type实现,就相当于:
    def bark(self):
        print('wang wang ..')
    
    # @staticmethod也是这样用
    @classmethod  
    def eat(self):
        print('i am eating...')
    
    Dog = type('Dog', (object,), {'bark': bark, 'eat': eat})
    
    # -----------------------------
    # 来试验一下:
    dog = Dog()
    dog.eat()
    dog.bark()
    
    

    输出结果:

    i am eating...
    wang wang ..
    

    4.__metaclass__自定义元类:

    • python3中:
    def say_hello(self):
        print('hello, I am ' + str(self))
    
    
    def my_type(class_name, class_fathers, class_attr):
        class_attr['say_hello'] = say_hello  # 给属性列表中加入say_hello
        return type(class_name, class_fathers, class_attr)
    
    
    class Foo(object, metaclass=my_type):  # 用指定的元类来创建类(python3中需要这样用metaclass)
        pass
    
    print(Foo)
    
    a = Foo()
    print(a)
    a.say_hello()  # Foo对象拥有了say_hello的方法
    
    
    • python2中:
    def say_hello(self):
        print('hello, I am ' + str(self))
    
    
    def my_type(class_name, class_fathers, class_attr):
        class_attr['say_hello'] = say_hello  # 给属性列表中加入say_hello
        return type(class_name, class_fathers, class_attr)
    
    
    class Foo(object):  # 用指定的元类来创建类
        __metaclass__ = my_type   # (python2中需要这样用metaclass)
    
    print(Foo)
    
    a = Foo()
    print(a)
    a.say_hello()  # Foo对象拥有了say_hello的方法
    
    
    • metaclass可以用来给类做一些初始化(可以继承父类,没谁用这个)。其实metaclass一般情况下没什么用,但了解了总算是更加了解了python的底层。

  • 相关阅读:
    fiddler如何抓取夜神模拟器上的包
    关于在虚拟机上安装iOS所遇到的问题
    ADB WiFi连接手机
    ADB命令总结(1)
    ADB连接手机遇到的问题:list of devices attached
    win 7 查看端口被占用
    APP测试用例要考虑的一些方面
    什么是阿尔法测试?
    关于ADB push 出现failed to copy 'D:file.xtxt' to '/system/temp/' : Read-only file system 的报错信息解决办法
    ADB push 和ADB pull命令
  • 原文地址:https://www.cnblogs.com/PrettyTom/p/6663501.html
Copyright © 2011-2022 走看看