zoukankan      html  css  js  c++  java
  • class底层原理分析

    class底层原理分析

    class类名,会把类构造出来

    实际上是:元类实例化产生类 这个对象

    类实例化产生对象,一定是:类名()

    Person  类是由type实例化产生的,传一堆参数
    type()  调用类的__init__方法
    #type()
    type(object_or_name,bases,dict)
    object_or_name:类的名字,是个字符串
    base:是它的所有的父类,基类
    dict:名称空间,是一个字典
    

    通过type来直接产生类,不用class关键字了

    l={}
    exec('''
    school='oldboy'
    def __init__(self,name):
        self.name=name
    def score(self):
        print('分数是100')
    
    ''',{},l)
    def __init__(self,name):
        self.name=name
    
    # Person=type('Person',(object,),{'school':'oldboy','__init__':__init__})
    Person=type('Person',(object,),l)
    
    print(Person.__dict__)
    print(Person.__bases__)
    p=Person('nick')
    print(p.name)
    print(p.__dict__)
    #{'school': 'oldboy', '__init__': <function __init__ at 0x000002190DBD2F28>, 'score': <function score at 0x000002190DF44488>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
    (<class 'object'>,)
    nick
    {'name': 'nick'}
    
    

    class 底层就是调用type来实例化产生类(对象)

    class Person:
        school='oldboy'
        def __init__(self,name):
            self.name=name
        def score(self):
            print('分数是100')
    a=Person
    p=Person('nick')
    
    

    exec() eval()区别

    #通过exec可以执行动态Python代码,类似Javascript的eval功能;而Python中的eval函数可以计算Python表达式,并返回结果;(exec不返回结果,print(eval("…"))打印None);
    
    l={}
    exec('''
    school='oldboy'
    def __init__(self,name):
        self.name=name
    def score(self):
        print('分数是100')
    ''',{},l)
    
    print(l)
    g={ 'x':1,'y':2}
    l={}
    exec('''
    global x
    x=100
    z=200
    m=300
    ''',g,l)
    print(g)
    print(l)
    
  • 相关阅读:
    Android ListView 列表视图
    android handler msg的使用 实现进度条
    Intent 传递数据
    微服务-springcloud
    微服务-dubbo学习
    日志收集系统
    微服务追踪
    链表有环判断,快慢指针两种方法/合并链表/删除重复元素/二分递归和while
    算法练习,链表二分最大n个
    池以及barrier简单
  • 原文地址:https://www.cnblogs.com/aden668/p/11453392.html
Copyright © 2011-2022 走看看