zoukankan      html  css  js  c++  java
  • python元编程3【type类继承和__new__,__init__参数传递】

    
    
    class SetterAwareType(type):    # 元类
        def __new__(cls, *args):
            # print('in SetterAwareType __new__')
            # print(type(type.__new__(cls, 'hehehe',(object,), {})))
            return type.__new__(cls, 'hehehe',(object,), {})  # 'name' 直接传入了
    
        def __init__(cls,  *args):
            '''
            # 这里的init不是self,传入的是__new__类似的,打印print(cls, args)结果如下
            1. a = ModelObject()
            2. class C(a)
            1. <class '__main__.hehehe'> ()
            2. <class '__main__.hehehe'> ('C', (<class '__main__.hehehe'>,), {'__module__': '__main__', '__qualname__': 'C', '__init__': <function C.__init__ at 0x000001B83DDC68B8>})
            '''
            # print(cls, args)
            # print('in SetterAwareType __init__')
            # return super(SetterAwareType, cls).__init__(cls,  *args)   # 创建 class C(a) 时候报错 type.__init__() takes 1 or 3 arguments
            return super(SetterAwareType, cls).__init__(cls, )
            # return type.__init__(cls, *args)                    # TypeError: type.__init__() takes 1 or 3 arguments
    
    
    class ModelObject(SetterAwareType):
        def test(self):
            print('in ModelObject copy')
    
    a = ModelObject()  # _init__ 参数 <class '__main__.hehehe'> ()
    
    class C(a): # _init__ 参数 <class '__main__.hehehe'> ('C', (<class '__main__.hehehe'>,), {'__module__': '__main__', '__qualname__': 'C', '__init__': <function C.__init__ at 0x000002445ED868B8>})
        pass
    
    print(type(SetterAwareType))  #  type 元类
    print(type(ModelObject))      #  type 元类
    
    print('a', a)
    print(type(a))    # a 是class hehehe,属于ModelObject class
    
    b=a()
    print('b', b)
    print(type(b))    # b 是obj hehehe,属于hehehe class
    
    
    a.test()          # 类中的函数
    # b.test()        #obj中报错 # AttributeError: 'hehehe' object has no attribute 'test'
    
    c = C()
    # c.test()          # AttributeError: 'hehehe' object has no attribute 'test'
    
    
  • 相关阅读:
    修改编译8266NodeMCU固件 打开各种模块以及修改支持智能配网
    3实现8266智能配网并打印出ip地址 8266 lua nodemcu 智能配网 一键配网
    8266 开发环境教程 nodemcu lua开发8266教程 输出世界你好
    代码提交量查询
    antd DatePicker框日期限制
    form表单设置值
    a标签传参数
    css获取页面高度,定位部分信息
    Form自定义校验
    下拉框可输入或输入为下拉框对应的值
  • 原文地址:https://www.cnblogs.com/amize/p/14684780.html
Copyright © 2011-2022 走看看