标签:level mat div not pre float deb span one
1.利用重写__setattr__来实现。
import logging logger = logging.getLogger(‘logger‘) streamhandler = logging.StreamHandler() logger.setLevel(logging.DEBUG) streamhandler.setLevel(logging.DEBUG) streamhandler.setFormatter(logging.Formatter( ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)) logger.addHandler(streamhandler) def typeassist(**kwargs): def new_cls(cls): def redefine(self, key, value): if not isinstance(value, kwargs[key]): logger.log(level=logging.ERROR, msg=‘TypeError‘) self.__dict__[key] = None else: self.__dict__[key] = value setattr(cls, ‘__setattr__‘, redefine) return cls return new_cls @typeassist(name=str, age=int, result=float) class Student: def __init__(self, name, age, result): self.name = name self.age = age self.result = result def __str__(self): return str(self.__dict__) m = Student(‘sasd‘, 56, 45.0) p = Student(‘SSS‘, 12, 4) print(p) print(m)
2.利用描述符来实现。
标签:level mat div not pre float deb span one
原文地址:https://www.cnblogs.com/poincare/p/9094746.html