我使用的 API 定义了这样的方法:
def show_prop(object, propname): #...
它应该做的是通过调用getattr(object, propname)
在屏幕上显示属性并允许用户更改属性,从而产生setattr(object, propname)
.
我无法更改该行为,但我想使用 API 向用户显示局部变量并接收用户的正常反馈?
我想到了一个描述当前范围和可用变量的构建变量,有点像本地 __dict__
但我还没有找到这样的东西。
userinput = "Default input"
show_prop(__mysterious_unknown__, 'userinput')
# Do something exciting with the changed userinput
这可以实现吗?
最佳答案
没有。本地写入访问只能直接在作用域或使用 nonlocal
的嵌套作用域中完成(仅限 Python3)。
Python 没有“指针”的概念,指定可写位置的唯一方法是传递对容器的引用和成员的“名称”(或数组的索引、数组的键)字典)。
但是,您可以做的是为此动态创建一个小对象:
class Bunch:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def foo():
my_local = 42
...
myobj = Bunch(my_local=my_local) # create the dummy instance
show_prop(myobj, "my_local") # call the original code
my_local = myobj.my_local # get modified value back
...
在 Python3 中,可以创建一个神奇的对象实例,当写入成员时,该实例将动态改变本地对象(使用新的 Python3 nonlocal
关键字以及属性或 __getattr__
/__setattr__
包罗万象)。除非确实需要,否则我不会选择这种奇怪的魔法......
例如:
def foo(obj, name):
# the fixed API
setattr(obj, name, 1 + getattr(obj, name))
def bar():
myloc = 11
# magic class...
class MyClass:
def __getattr__(self, name):
# accessing any member returns the current value of the local
return myloc
def __setattr__(self, name, value):
# writing any member will mutate the local (requires Python3)
nonlocal myloc
myloc = value
foo(MyClass(), "myloc")
print(myloc) # here myloc will have been incremented
bar()
关于python - 描述当前范围的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31658707/