• 【7.5】自定义元类


    元类是什么--元类是创建类的类

     1 #!/user/bin/env python
     2 # -*- coding:utf-8 -*-
     3 
     4 # 类也是对象,type创建类的类
     5 
     6 
     7 def create_class(name):
     8     if name == 'user':
     9         class User:
    10             def __str__(self):
    11                 return 'user'
    12         return User
    13     elif name == 'company':
    14         class Company:
    15             def __str__(self):
    16                 return 'company'
    17         return Company
    18 
    19 
    20 # type动态创建类
    21 User = type('User', (), {})
    22 
    23 
    24 def say(self):
    25     return 'i am user'
    26 
    27 
    28 class BaseClass:
    29     def answer(self):
    30         return 'i am baseclass'
    31 
    32 
    33 # 什么是元类, 元类是创建类的类
    34 class MetaClass(type):
    35     def __new__(cls, *args, **kwargs):
    36         return super().__new__(cls, *args, **kwargs)
    37 
    38 
    39 class User(metaclass=MetaClass):
    40     def __init__(self, name):
    41         self.name = name
    42 
    43     def __str__(self):
    44         return 'user'
    45 
    46 
    47 # python 中类的实例化过程,会首先寻找metaclass, 通过metaclass去创建user类
    48 # type去创建类对象,实例
    49 
    50 
    51 if __name__ == '__main__':
    52     # MyClass = create_class('user')
    53     # my_obj = MyClass()
    54     # print(my_obj)
    55     User = type('User', (BaseClass,), {'name': 'user', 'say': say})
    56     user = User()
    57     print(user.name)
    58     print(user.say())
    59     print(user.answer())
    user
    i am user
    i am baseclass
    

      

  • 相关阅读:
    linux学习笔记--20150122
    破解LR11 sentinel stage failed
    Linux部署环境初学(Resin、jdk)
    MongoDB操作
    TestNG
    在iOS8 下用Swift 创建自定义的键盘
    iOS 8下简单,可交互式的通知
    设计模式:策略模式
    用Swift创建一个自定义,可调整的控件
    iOS7状态栏上有趣的渐变遮罩
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11268668.html
Copyright © 2020-2023  润新知