• 【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
    

      

  • 相关阅读:
    c#读取XML
    Javascript 自动计算生日
    Thread.currentThread()与setDaeMon(boolean c)方法
    StringBuffer类的delete()方法和deleteCharAt()方法
    getStackTrace()方法使用
    JDBC详解
    eclipse与idea路径不匹配
    Idea导入maven项目不自动识别pom.xml
    IDEA找不到或无法加载主类
    MySQL:主从复制与处从复制同步延迟
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11268668.html
Copyright © 2020-2023  润新知