Last active
March 5, 2020 19:17
-
-
Save w495/fff5b93bba3dbd473c793b05ba6a216a to your computer and use it in GitHub Desktop.
Простой пример добавление атрибута через метакласс
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import logging | |
class AddLoggerMeta(type): | |
def __new__(mcs, class_name, bases, attr_dict): | |
attr_dict[f'_{class_name}__logger'] = logging.getLogger(class_name) | |
return super().__new__(mcs, class_name, bases, attr_dict) | |
class Base(metaclass=AddLoggerMeta): | |
def base_function(self): | |
self.__logger.error('base_function') | |
@classmethod | |
def class_function(cls): | |
cls.__logger.error('class_function') | |
if __name__ == '__main__': | |
Base.class_function() | |
b = Base() | |
b.base_function() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment