0

我有以下课程:

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)

这个类将从多个类中实例化。在以下行中:

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

我想记录在Connection类中调用__init __ 方法的类。这可能吗 ?

例如,基于以下内容:

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

我想看到这个记录:

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

1 回答 1

1

像这样的东西?

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()

输出:

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)
于 2012-10-20T13:56:03.023 回答