繁体   English   中英

如何获取调用__init__方法的子类

[英]How to get the child class that called the __init__ method

我有以下课程:

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"

像这样吗

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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