[英]How to get all the local variables defined inside the function in python?
[英]Python: How to get all of the local variables defined in another module
有没有办法引用在不同模块中定义的局部变量?
例如,我有两个文件:framework.py和user_code.py:
framework.py:
from kivy.app import App
class BASE_A:
pass
class MyApp(App):
def on_start(self):
'''Here I'd like to get a reference to sub-classes of BASE_A and
instantiated objects of these sub-classes, defined in the file
"user_code.py" such as a1, a2, as well as the class A itself,
without explicitly passing them to MyApp's instance.
'''
user_code.py:
from framework import MyApp
class A(BASE_A):
pass
app = MyApp()
a1 = A()
a2 = A()
app.run()
我想做的就是以某种方式获得对对象a1和a2以及类A的引用,这些对象都在user_code.py中定义。 我想在on_start方法中使用它们,该方法在app.run()中调用。
例如,是否有可能获得对MyApp对象定义范围的引用(user_code.py)?
有兴趣的人的一些背景知识:
我知道这是一个奇怪的问题,但原因是:
我正在编写一个Python框架,用于基于Arduino创建用于自制乐器的定制GUI控制程序。 它称为Instrumentino (位于GitHub上 ),我目前正在开发版本2。
为了使人们能够使用该框架,他们需要定义一个系统描述文件(在示例中为user_code.py ),在其中声明他们在系统中使用的是什么部分(python对象)以及系统应采取的动作类型执行(python类)。
我想要实现的目的是在MyApp的on_start中自动识别这些对象和类,而不要求用户显式传递这些对象和类,以使用户代码更整洁。 避免使用诸如以下代码的含义:
app.add_object(a1)
app.add_object(a2)
app.add_class(A)
Python中的新型类具有名为__subclasses__
的方法,该方法返回到目前为止已定义的所有直接子类的列表。 您可以使用它来获取示例中的A
类,只需调用BASE_A.__subclasses__()
(如果您使用的是Python 2,则还需要更改BASE_A
以从object
继承)。 有关更多详细信息,请参见此问题及其答案 (尤其是递归获取所有子类的函数)。
至于访问实例,为此,您可能应该向基类中添加一些代码,也许将__new__
创建的实例__new__
到某种数据结构中(例如, weakset
)。 有关该部分的更多信息,请参见此问题及其答案 。 实际上,考虑到这一点,如果您将实例放入某个位置的集中式数据结构中(例如,不在每个子类的属性中),则可能不需要该函数来搜索类,因为您可以检查type
实例并找到正在使用的子类。
您的问题有点不合逻辑。
由于Python会顺序解释代码: b
在a initialization
之前未定义。
如果你可以设置b
前a
则:
b = None # global variable
class A():
global b
def __init__(self):
'''Here I'd like to get a reference to b (of type B) without passing it as an argument'''
class B_BASE():
pass
class B(B_BASE):
def __init__(self):
pass
if __name__ == '__main__':
b = B()
a = A()
我不建议这样做,因为我发现这不干净。 由于您对b
中a
b
有依赖性,因此应将其作为参数传递给A class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.