如何获取Python中的类的文件路径? [英] How do I get the filepath for a class in Python?

查看:1663
本文介绍了如何获取Python中的类的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中给定一个类C,我如何确定该类在哪个文件中定义?我需要的东西,可以工作的类C或C的一个实例。

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 off C.

我这样做的原因是因为我一般是一个粉丝属于同一文件夹中的文件。我想创建一个类,使用Django模板将其自身呈现为HTML。基本实现应该根据类定义的文件名来推断模板的文件名。

The reason I am doing this, is because I am generally a fan off 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.

假设我把一个类LocationArtifact放在文件base / artifacts py,那么我想要的默认行为是模板名称是base / LocationArtifact.html。

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".

推荐答案

可以使用检查模块,例如:

import inspect
inspect.getfile(C.__class__)

这篇关于如何获取Python中的类的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆