I have 2 classes:

class Logger: def __init__(self, name): self.name = name def log(self, log): # Этот класс должен перехватить имя класса, который его вызовет with open(self.name, "a+") as log_file: log_file.write(log) return log class SomeClass: def __init__(self): self.logger = Logger("log.txt") def log_some(self, message): print(message) self.logger.log(message) return message 

And I need the Logger class to be able to get the name of the class that called the method when called from another class of the log() method. There is a way to get the name of the class in which the method is defined

 self.__class__.__name__ 

But in this case, he will be useless to me. If more options?

  • If you want to log errors, traceback may be useful. There are useful buns. - Bogdan
  • As per Sergey Gornostaev, it is better to pass to the class method information about the other class calling it explicitly. - strawdog

2 answers 2

It would be better to pass information about the calling class to the Logger constructor. But you can organize all sorts of crutches based on the analysis of the call stack:

 import inspect def get_caller_name(): frames = inspect.getouterframes(inspect.currentframe(), 3) if len(frames) > 1: info = frames[1] args, _, _, values = inspect.getargvalues(info.frame) obj = values.get('self') if obj is not None: return '{}.{}'.format(obj.__class__.__name__, info.function) return info.function 
  • ABOUT! I suspected and feared just such black magic. Not what I would recommend to use - but respect! - Alex Yu

Short answer: no way

Detailed response

We look at the signature of Logger.log :

 class Logger: ..... def log(self, log): # Этот класс должен перехватить имя класса, который его вызовет with open(self.name, "a+") as log_file: log_file.write(log) return log 

And we see that all OOP is the only self that will point to the Logger instance.

Indications on caller - no, and correspondingly .. answer: no way .

Black magic

If you want to feel like a powerful magician and magician and become famous among colleagues forever - you can, of course, try to dig something with sys.settrace , frame manipulation, customize globals / locals neemspaces, dizasm and dig into baytkod.

But: I don’t know and recommend any simple recipe for such magic (except for advanced training).