如何获取 Python 中类的文件路径?
给定 Python 中的类 C
,我如何确定该类是在哪个文件中定义的? 我需要一些可以从 C
类或 C
实例运行的东西。
我这样做是因为我通常喜欢将属于同一文件夹的文件放在一起。 我想创建一个使用 Django 模板将自身呈现为 HTML 的类。 基本实现应该根据定义类的文件名推断模板的文件名。
假设我将一个类 LocationArtifact
放在文件“base/artifacts.py”中,那么我想要默认值行为是模板名称为“base/LocationArtifact.html”。
Given a class C
in Python, how can I determine which file the class was defined in? I need something that can work from either the class C
, or from an instance of C
.
I am doing this because I am generally a fan of putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.
Say I put a class LocationArtifact
in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 inspect 模块,如下所示:
You can use the inspect module, like this:
尝试:
try:
这对 Django 来说是错误的做法,而且确实是强迫性的。
典型的 Django 应用模式是:
This is the wrong approach for Django and really forcing things.
The typical Django app pattern is:
您可以使用错误来获取您的类的路径
You can use the error to get the path of your class