我在给定的 Python 模块中定义了一个类。从其他几个 python 文件中,我将创建所述类的实例。实例在对象创建时注册自己,即在 __init__()
期间,在单例注册表对象中。我想从第三种类型的 python 文件访问注册表,查看其中的对象,并能够找出这些对象是在哪些文件中预先创建的。
代码示例可能如下所示:
Python 模块文件:'/Users/myself/code/myobjectmodule.py':
@singleton
class Registry(object):
def __init__(self):
self.objects = {}
class MyObject(object):
def __init__(self, object_name):
self.object_name = object_name
Registry().objects[self.object_name] = self
singleton
装饰器根据 http://www.python.org/dev/peps/pep-0318/#examples
实例创建 python 文件:'/Users/myself/code/instance_creation_python_file.py':
from myobjectmodule import MyObject
A = MyObject('Foo')
第三个 python 文件:'/Users/myself/code/registry_access.py':
from myobjectmodule import Registry
registry = Registry()
foo = registry.objects['Foo']
现在,我想要一个方法 foo.get_file_of_object_creation()
。
如何实现这个方法?
编辑:
采用这种方法的原因是以下场景:
1. 框架定义了一组对象,这些对象应指定数据源并包含加载后的数据(MyObject)。
2. 使用此框架的应用程序应指定这些对象并使用它们。每个应用程序都保存在一个 .py 文件或一个文件夹中,该文件或文件夹还通过其名称指定应用程序的名称。
3. 引擎为所有应用程序提供功能,但对于某些功能,引擎需要知道哪些对象来自哪个应用程序/文件。
最佳答案
在不考虑为什么要这样做的优点的情况下,这里有一种方法可以做到:
# assume the file is saved as "temp.py"
import inspect
class RegisteredObject(object):
def __new__(cls, *args, **kwargs):
new_instance = super(RegisteredObject, cls).__new__(cls, *args, **kwargs)
stack_trace = inspect.stack()
created_at = '%s:%d' % (
stack_trace[1][1], stack_trace[1][2])
new_instance.created_at = created_at
return new_instance
def get_file_of_object_creation(self):
return self.created_at
class MyObject(RegisteredObject):
pass
def create_A():
return MyObject()
def create_B():
return MyObject()
if __name__ == '__main__':
t1 = create_A()
t2 = create_B()
t3 = create_A()
t4 = create_B()
t5 = MyObject()
print '"t1" was created at "%s"' % t1.get_file_of_object_creation()
print '"t2" was created at "%s"' % t2.get_file_of_object_creation()
print '"t3" was created at "%s"' % t3.get_file_of_object_creation()
print '"t4" was created at "%s"' % t4.get_file_of_object_creation()
print '"t5" was created at "%s"' % t5.get_file_of_object_creation()
输出:
$ python temp.py
"t1" was created at "temp.py:19"
"t2" was created at "temp.py:22"
"t3" was created at "temp.py:19"
"t4" was created at "temp.py:22"
"t5" was created at "temp.py:29"
关于python - 如何知道对象在 Python 中实例化的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22147050/