gpt4 book ai didi

python - Python mixin 是否可以访问全局变量?

转载 作者:行者123 更新时间:2023-12-01 05:43:36 24 4
gpt4 key购买 nike

我有一个 mixin,它定义了要在另一个类中重写的 finalize_response() 方法:

class APILoggingMixin(object):
"""
Provides logging functionality by overriding finalize_response().
Intended to be mixed in with any rest_framework.views.APIView
"""
def finalize_response(self, request, response, *args, **kwargs):
logger.info('Some message.')
return super(APILoggingMixin, self).finalize_response(request, response, *args, **kwargs)

还有一个实现 finalize_response() 方法的类。在同一模块中,定义了 logger 全局变量:

import logging
logger = logging.getLogger(__name__)

class CategoryDetail(APILoggingMixin, generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a Category.
"""
model = Category
serializer_class = CategorySerializer
permission_classes = (permissions.IsAuthenticated,)

如何访问 mixin 中的 logger 变量?

最佳答案

意识到APILoggingMixin.finalize_response采用self(它是一个CategoryDe​​tail实例),我们可以将记录器附加到CategoryDe​​tail

class CategoryDetail(...):
logger = logger

class APILoggingMixin(object):
def finalize_response(self, ...):
self.logger.info('Some message.')

# Or through get_logger()
class CategoryDetail(...):
def get_logger(self):
return logger

class APILoggingMixin(object):
def finalize_response(self, ...):
self.get_logger().info('Some message.')

def get_logger(self):
raise NotImplementedError

# Or take advantage of the fact that `self.__module__` equals to `__name__` in the module of `CategoryDetail`
class APILoggingMixin(object):
def finalize_response(self, ...):
logger = logging.getLogger(self.__module__)
logger.info('Some message.')

关于python - Python mixin 是否可以访问全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16826821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com