python之type

先上代码

class Foo:
    pass

print(Foo,  type(Foo))
print(type, type(type))

'''
    <class '__main__.Foo'> <class 'type'>
    <class 'type'> <class 'type'>

'''

Python中万物皆对象,所有用来创建对象的类,本身也对象,类是type类的对象

type类叫做元类,是所有元类的类

元类: 造类的类 -类的类

  -- 控制类的产生

  --控制类的对象的产生

在type的init方法中

def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
        """
        type(object_or_name, bases, dict)
        type(object) -> the object's type
        type(name, bases, dict) -> a new type
        # (copied from class doc)
        """
        pass
type(name, bases, dict) -> a new type
name为类的名字 'C'
bases为继承的基类 (object,)
dict为名称空间 {}
class Foo:
    pass


print(Foo, type(Foo))
C = type('C', (object,), {})
print(C, type(C))
C.name = 123
print(C.name)
'''

  <class '__main__.Foo'> <class 'type'>
  <class '__main__.C'> <class 'type'>
  123

'''

由此可见使用type可以直接创建一个类

使用exec给类创建名称空间

s = '''
my_a = 10
my_b = 20
def __init__(self, name):
    self.name = name
@classmethod
def print_msg(cls,msg):
    print(msg)
'''

dic = {}
exec(s, {}, dic)

C = type('C', (object,), dic)
print(C, type(C))
print(C.__dict__)
# C() # 报错  __init__中带有一个参数
C('yyf')  # 不报错
C.print_msg(123)
'''

  <class '__main__.C'> <class 'type'>
  {'my_a': 10, 'my_b': 20, '__init__': <function __init__ at 0x01AA0858>, 'print_msg': <classmethod object at 0x01AD9950>, '__module__': '__main__', '__dict__': <att  ribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}
  123

'''

猜你喜欢

转载自www.cnblogs.com/yuyafeng/p/10957404.html