zoukankan      html  css  js  c++  java
  • 元类

    一切的类都是通过type这个类来创建的,例如:

     1 class Foo:
     2     a = 1
     3     pass
     4 
     5 
     6 print(type(Foo))
     7 print(Foo.__dict__)
     8 
     9 
    10 def __init__(self, name, age):
    11     self.name = name
    12     self.age = age
    13 
    14 
    15 f1 = type('crazy', (object,), {'a': 1, '__init__': __init__})
    16 print(type(f1))
    17 print(f1.__dict__)
    18 ff = f1('alex',18)
    19 print(ff.name)
    20 print(ff.age)
    21 输出:
    22 <class 'type'>
    23 {'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}
    24 <class 'type'>
    25 {'a': 1, '__init__': <function __init__ at 0x00978A00>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'crazy' objects>, '__weakref__': <attribute '__weakref__' of 'crazy' objects>, '__doc__': None}
    26 alex
    27 18
     1 class Mytype(type):
     2     def __init__(self, a, b, c):
     3         print(a)
     4         print(b)
     5         print(c)
     6 
     7     def __call__(self, *args, **kwargs):
     8         obj = object.__new__(self)
     9         self.__init__(obj, *args, **kwargs)
    10         return obj
    11 
    12 
    13 class Foo(metaclass=Mytype):  # Foo = Mytype(Foo,'Foo',(),{})
    14     def __init__(self, name, age):
    15         self.name = name
    16         self.age = age
    17 
    18 
    19 f1 = Foo('alex', 28)
    20 print(f1.__dict__)
    21 输出:
    22 Foo
    23 ()
    24 {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x00698A00>}
    25 {'name': 'alex', 'age': 28}
  • 相关阅读:
    省队集训 Day1 残缺的字符串
    省队集训 Day3 吴清华
    省队集训 Day3 陈姚班
    Java多线程中的join方法
    Java多线程同步机制之同步块(方法)——synchronized
    java-实用的sql语句
    java-分页之页面分页
    java下实现调用oracle的存储过程和函数
    java-MySQL存储过程
    MySQL存储过程
  • 原文地址:https://www.cnblogs.com/ch2020/p/12506593.html
Copyright © 2011-2022 走看看