class A (): DEF the __init__ (Self, name): the self.name = name Print ( " create an instance of " ) A = type ( " A " , (A,), { " name " : " Jiao " }) Print (a) # <class 'in __main __. a'> Print (a.name) # Jiao Print (a ( " Jiang " )) # create an instance #<__main__.a object at 0x00000280A973AA58>
class UpperAttrMetaClass(type): def __new__(cls,class_name,class_parents,class_attr, *args, **kwargs): print("__new__") class_attr['name'] = "jiao" return type.__new__(cls,class_name,class_parents,class_attr) def __init__(self,*args,**kwargs): print("__init__") super().__init__(*args, **kwargs) self.__cache = {} def __call__(self, *args, **kwargs): print("__call__") if args in self.__cache: return self.__cache[args] else: obj = super().__call__(*args) self.__cache[args] = obj return obj class A(metaclass=UpperAttrMetaClass): def __init__(self,name): self.name = name print("a.__init__")
class Singleton(type): def __init__(cls,*args,**kwargs): cls.__instance = None super().__init__(*args,**kwargs) def __call__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = super().__call__(*args,**kwargs) return cls.__instance else: return cls.__instance class Spam(metaclass=Singleton): def __init__(self): print("Creating Spam")
2. Cache Mode
import weakref class Cached(type): def __init__(cls,*args,**kwargs): super().__init__(*args,**kwargs) cls.__cache = weakref.WeakValueDictionary() def __call__(cls, *args, **kwargs): if args in cls.__cache: return cls.__cache[args] else: obj = super().__call__(*args) cls.__cache[args] = obj return obj class Spams(metaclass=Cached): def __init__(self,name): print("Creating Spam({!r})".format(name)) self.name = name
from collections import OrderedDict class Typed: _excepted_type = type(None) def __init__(self,name=None): self._name = name def __set__(self, instance, value): if not isinstance(value,self._excepted_type): raise TypeError("Excepted"+str(self._excepted_type)) instance.__dict__[self._name] = value class Integer(Typed): _excepted_type = int class Float(Typed): _excepted_type = float class String(Typed): _excepted_type = str class OrderedMeta(type): def __new__(cls, clsname,bases,clsdict): d = dict(clsdict) order = [] for name,value in clsdict.items(): if isinstance(value,Typed): value._name = name order.append(name) d['_order'] = Order return type. __New__ is (CLS, clsname, bases, D) @classmethod DEF __prepare__ (metacls, name, bases): return OrderedDict () # Note: __ prepare__ This method begins when the class definition of a call, the call when the class name and the base class name as an argument, it must return a mapping object, for processing the class definition body invoked # EG. class Structure (the metaclass that = OrderedMeta): DEF as_csv (Self): return ' , ' .join (STR ( getattr (Self, name)) for name in self._order) class Stock (= the metaclass that OrderedMeta): name = String() shares = Integer() price = Float() def __init__(self,name,shares,price): self.name = name self.shares = shares self.price = price s = Stock("haha",23,23.3) print(s.name) s = Stock(34,23,34) # print(s.as_csv())