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
原文地址:https://www.cnblogs.com/luodaoqi/p/11528875.html
时间: 2024-10-04 20:38:35