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)

猜你喜欢

转载自www.cnblogs.com/aden668/p/11453392.html