#知识储备exec 使用,
#参数1 字符串形式的命令,把字符串中的指令直接执行
#参数2 全局作用域 ,2中,全局和局部,字典形式,如果不指定默认使用globals()
#参数3,局部作用域, 如果不指定默认使用locals()
g={ "x":1, "y":2 } l={} exec(""" global x,m x=10 m=100 z=3 """,g,l) print(g) print(l)
#python 一切皆对象,对象可以怎么用
#1,都可以被引用
#2.都可以当做函数参数传入
#3.都可以当做返回值
#4.都可以当做容器类的元素
#但凡符合4个,都是对象
#类也是对象 Foo=type()
# class Foo:
# pass
# obj=Foo()
# print(type(obj)) #<class ‘__main__.Foo‘>
# print(type(Foo)) #<class ‘type‘>
#什么叫元类
# 造类的类叫元类,默认所有用class定义的类,造他们的类都是type
#定义类的两种方式
#一种,class 类
class Chinese:#实际是调用type类的实例化 county="China" def __init__(self,name,age): self.name=name self.age=age def talk(self): print("%s is talking "% self.name) print(Chinese) obj=Chinese("EGON",18) print(obj.name)
#方式二 type 元类产生
#定义类的三要素.类名,类的基类,类的名称空间
class_name="China" class_bases=(object,)#默认object class_body=""" county="China" def __init__(self,name,age): self.name=name self.age=age def talk(self): print("%s is talking "% self.name) """ class_dic={} exec(class_body,globals(),class_dic) print(class_dic) Chinese1=type(class_name,class_bases,class_dic) print(Chinese1) obj1=Chinese1("EGON",18) print(obj1.name)
原文:https://www.cnblogs.com/xh716/p/10526925.html