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

    class 类名 会把类构造出来

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

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

    Person 类是由type实例化产生,传一堆参数
    type() 调用类的__init__方法
    type()
    type(object_or_name,bases,dict)
    object_or_name 类的名字,是个字符串
    bases:是它的所有的父类,基类
    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,),1) 
    
    #print(Person.__dict__)
    print(Person.__bases__)
    #p = Person('nick')
    print(p.name)
    print(p.__dict__)
    #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()的区别
    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)
    
    x = 1
    y = 2
    def test():
      global x
      x = 100
      z = 200
      m = 300
    
  • 相关阅读:
    离职or not 离职
    RelativeLayout总结
    MVC中小试了一下Jquery
    tricks about andor in python
    【回旋数字】c语言实现
    退役?
    HDU4546 比赛难度
    WEB页面导出为EXCEL文档的方法
    开始→运行→命令
    控制Repeater显示列数
  • 原文地址:https://www.cnblogs.com/luodaoqi/p/11528875.html
Copyright © 2011-2022 走看看