面象对象的反射和单列模式

a ="普通变量a"
b ="普通变量b"
A ="普通常量A"
B ="普通常量B"
import sys
def func():
print("func,function")
def func1():
print("func1,function")
while 1:
res = input("<<<:").strip()
if res.upper() == "Q":
break
if hasattr(sys.modules[__name__],res):
object =getattr(sys.modules[__name__],res)
if callable(object):
object()
else:
print(object)
else:
print("Error")


单例模式
class Teacher:
flag = None
def __new__(cls,*args,**kwargs):
if cls.flag is None:
cls.flag = object.__new__(cls)
return cls.flag
def __init__(self,name):
self.name = name
alex1 = Teacher("alex")
alex2 = Teacher("alex")
yuan = Teacher("yuan")
print(alex1.name)
print(yuan.name)

猜你喜欢

转载自www.cnblogs.com/liurenli/p/10034299.html