我想要
LoggerMixin
记录
info
)self.brand
和self.wheel
)。我怎样才能实现这个目标?请参阅下面我目前所在的位置:
import logging
class LoggerMixin:
def log(self):
logging.basicConfig(level=logging.INFO, format='%(funcName)s-%(message)s')
return logging.info(f'func name is {self.__class__.__name__}')
class Car(LoggerMixin):
def __init__(self, brand: str, wheel: int):
self.brand = brand
self.wheel = wheel
def info(self):
print(f'my brand is {self.brand} and i have {self.wheel} wheel')
obj1 = Car(brand='bmw', wheel=4)
obj1.info()
basicConfig
可以在类外定义。__init__()
添加一个 LoggerMixin
方法。LoggerMixin
来初始化继承的super().__init__()
对象。logging.info()
本地调用 self.logger
,以便它正确识别 funcName
。我的建议还有进一步的小改进:
import logging
logging.basicConfig(level=logging.INFO, format='%(funcName)s – %(message)s')
class LoggerMixin:
def __init__(self):
self.logger = logging.getLogger()
class Car(LoggerMixin):
def __init__(self, brand: str, wheel: int):
super().__init__()
self.brand = brand
self.wheel = wheel
def info(self):
self.logger.info(f'My brand is {self.brand} and I have {self.wheel} wheel(s)')
obj1 = Car(brand='bmw', wheel=4)
obj1.info()