简体   繁体   中英

How to get the child class that called the __init__ method

I have the following class:

import cfg
import sqlite3
import logging

# logger = logging ......

class Connection:
    def __init__(self):
        try:
            self.connection = sqlite3.connect(cfg.pathToDatabase)
            self.connection.row_factory = sqlite3.Row
            self.cursor = self.connection.cursor()
            logger.info("Connection to database at " + cfg.pathToDatabase + " successful")
        except Exception, e:
            logger.critical("Error connecting to database")
            logger.exception(e)

This class will be instantiated from multiple classes. In the following line:

logger.info("Connection to database at " + cfg.pathToDatabase + " successful")

I would like to log the class that called the __ init __ method in the Connection class. Is this possible ?

for example, based on the following:

class Child:
    def __init__(self):
        self.connection = Connection()

I would like to see this logged:

"Connection to database at data.sqlite successful from class: Child"

Something like this?

import traceback, sys

class C:
    def __init__(self):
        try:
            raise StopIteration
        except StopIteration:
            tb = sys.exc_info()[2]
            stack = traceback.extract_stack(tb.tb_frame)
            f = stack[-2]
            print "I was called from %s %s (%s:%s)" % (f[2], f[3], f[0], f[1])

class A:
    def __init__(self):
        self.c = C()

def foo():
    A()
    return C()

def main():
    C()
    foo()

if __name__ == '__main__':
    main()

Output:

I was called from main C() (test.py:22)
I was called from __init__ self.c = C() (test.py:15)
I was called from foo return C() (test.py:19)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM