# 将字符串作为执行目标,得到响应结果
# eval常用作类型转换:该函数执行完有返回值
dic_str = "{'a':1, 'b':2, 'c':3}"
dic = eval(dic)
# exec拥有执行更复杂的字符串:可以形成名称空间
class_str = = '''
a = 10
b = 20
@classmethod
def fn(cls):
pass
'''
local_dic = {}
# 可以操作全局与局部两个名称空间,一般不用关心全局名称空间
exec(class_str, {}, local_dic)
元类
# 元类:类的类
# 通过class产生的类,也是对象,而元类就是用来产生该对象的类
local_str = """
def __init__(self, name, age):
self.name = name
self.age = age
def study(self):
print(self.name + '在学习')
"""
local_dic = {}
exec(local_str, {}, local_dic)
Student = type('Student', (), l_d)
print(Student)
自定义元类
# 控制类的产生过程,以及该类对象的产生过程
class MyMeta(type):
# 控制类的创建过程
def __init__(cls, class_name, bases, namespace):
print(cls, class_name, bases, namespace)
super().__init__(class_name, bases, namespace)
def __call__(cls, *args, **kwargs):
obj = object.__new__(cls)
cls.__init__(obj, *args, **kwargs)
return obj
# Student类与Student类的对象产生都可以备元类MyMeta控制
class Student(metaclass=MyMeta):
def __init__(self, name, age):
self.name = name
self.age = age
stu = Student('owen', 18)
print(stu.name)
元类的应用
class MyMeta(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = cls.__new__(cls)
cls.instance.__init__(*args, **kwargs)
return cls.instance
class A(metaclass=MyMeta):
def __init__(self):
self.ip = '1.1.1.0'