简体   繁体   English

如何获取子类的文件名?

[英]How to get filename of subclass?

How to get the filename of the subclass?如何获取子类的文件名?

Example:例子:

base.py : base.py

class BaseClass:
    def __init__(self):
        # How to get the path "./main1.py"?

main1.py : main1.py

from base import BaseClass

class MainClass1(BaseClass):
    pass

Remember that self in BaseClass.__init__ is an instance of the actual class that's being initialised.请记住, selfBaseClass.__init__是真实被初始化实际的类的实例。 Therefore, one solution, is to ask that class which module it came from, and then from the path for that module:因此,一种解决方案是询问该类它来自哪个模块,然后询问该模块的路径:

import importlib

class BaseClass:
    def __init__(self):
        m = importlib.import_module(self.__module__)
        print m.__file__

I think there are probably a number of way you could end up with a module that you can't import though;我认为可能有多种方式最终会导致无法导入的模块; this doesn't feel like the most robust solution.感觉这不是最强大的解决方案。

If all you're trying to do is identify where the subclass came from, then probably combining the module name and class name is sufficient, since that should uniquely identify it:如果您要做的只是确定子类的来源,那么组合模块名和类名就足够了,因为这应该唯一标识它:

class BaseClass:
    def __init__(self):
        print "{}.{}".format(
            self.__module__,
            self.__class__.__name__
        )

You could do it by reaching back through the calling stack to get the global namespace of the caller of the BaseClass.__init__() method, and from that you can extract the name of the file it is in by using the value of the __file__ key in that namespace.您可以通过返回调用堆栈来获取BaseClass.__init__()方法的调用者的全局命名空间,然后您可以使用__file__键的值从中提取它所在的文件的名称在那个命名空间中。

Here's what I mean:这就是我的意思:

base.py : base.py

import sys

class BaseClass(object):
    def __init__(self):
        print('In BaseClass.__init__()')
        callers_path = sys._getframe(1).f_globals['__file__']
        print('  callers_path:', callers_path)

main1.py : main1.py

from base import BaseClass

class MainClass1(BaseClass):
    def __init(self):
        super().__init__()

mainclass1 = MainClass1()

Sample output of running main1.py :运行main1.py示例输出:

In BaseClass.__init__()
  callers_path: the\path\to\main1.py

I think you're looking to the wrong mechanism for your solution.我认为您正在寻找错误的解决方案机制。 Your comments suggest that what you want is an exception handler with minimal trace-back capability.您的评论表明您想要的是具有最小追溯功能的异常处理程序。 This is not something readily handled within the general class mechanism.这不是一般class机制中容易处理的事情。

Rather, you should look into Python's stack inspection capabilities.相反,您应该研究 Python 的堆栈检查功能。 Very simply, you want your __init__ method to report the file name of the calling sub-class.很简单,您希望__init__方法报告调用子类的文件名。 You can hammer this by requiring the caller to pass its own __file__ value.你可以通过要求调用者传递它自己的__file__值来解决这个问题。 In automated fashion, you can dig back one stack frame and access __file__ via that context record.以自动化方式,您可以回溯一个堆栈框架并通过该上下文记录访问__file__ Note that this approach assumes that the only time you need this information is when __init__ is called is directly from a sub-class method.请注意,此方法假定您需要此信息的唯一时间是直接从子类方法调用__init__

Is that enough to get you to the right documentation?这足以让您获得正确的文档吗?

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

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