• 原来Python类还有这么多花样


    """metaclass的作用是指定当前类由谁来创建"""
    
    
    # 第一种创建类的方式
    class Foo(object):
        name = "小强"     # 类的静态字段
    
        def func(self):
            return 666
    
    
    val = Foo()
    print(val.name)
    
    # 第二种创建类的方式
    Foo1 = type("Foo", (object,), {"name": "小强", "func": lambda self: 666})
    
    val1 = Foo1()
    print(val1.name)
    
    
    # 2.自定义type
    class YouType(type):
        pass
    
    
    class Foo2(object, metaclass=YouType):    # metaclass指定当前继承类
        name = "小老鼠"
    
        def func(self):
            return "猫不抓"
    
    
    val2 = Foo2()
    print(val2.name)
    
    Foo3 = YouType("Foo", (object,), {"name": "小老鼠", "func": lambda self: "猫不抓"})
    
    val3 = Foo3()
    print(val3.name)
    
    
    # 3.metaclass
    class MyType(type):
    
        def __init__(self, *args, **kwargs):
            super(MyType, self).__init__(*args, **kwargs)
    
        def __call__(cls, *args, **kwargs):
            obj = cls.__new__(cls)
            cls.__init__(obj, *args, **kwargs)
            return obj
    
    
    class Foo4(object, metaclass=MyType):
        name = "旺财"
    
        def __init__(self):
            pass
    
        def __new__(cls, *args, **kwargs):
            return object.__new__(cls)
    
        def func(self):
            return 666
    
    
    # Foo4是MyType的一个对象
    obj = Foo4()
    print(obj.name)
    View Code

    
    
  • 相关阅读:
    多线程的创建方式
    ArrayList 初探
    java创建对象的几种方式
    select2动态查询及多选
    RabbitMQ 消息发送、消息监听
    tr命令
    集群,分布式,微服务概念和区别理解
    xargs命令
    shell中的EOF用法
    字段分隔符IFS
  • 原文地址:https://www.cnblogs.com/Guishuzhe/p/9783188.html
Copyright © 2020-2023  润新知