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
    
  • 相关阅读:
    js中call,apply,bind方法的用法
    使用react脚手架初始化一个项目
    常用的CSS居中方式
    react组件之间的通信
    React脚手架less的安装
    js操作DOM的方法
    常用的ement语法
    本机系统通过SSH访问虚拟机中的Linux系统
    Java_amr格式转mp3
    linux/ubantu 安装 mysql 并且使其支持远程连接
  • 原文地址:https://www.cnblogs.com/luodaoqi/p/11528875.html
Copyright © 2011-2022 走看看