[英]Enter object namespace in Python
Is there a way to enter an object's namespace so that I can use its methods as though they were global?有没有办法输入对象的命名空间,以便我可以像使用全局方法一样使用它的方法? I was thinking of something using the with statement.
我在想一些使用 with 语句的东西。
class Bar():
def methodA(self):
# do stuff
def methodB(self):
# do more stuff
def __enter__(self):
# somehow enter object namespace / transfer methods into global namespace
def __exit__(self, *args):
# exit object namespace / get rid of globalized methods
foo = Bar()
with foo:
methodA() # all works fine
methodB()
methodA() # throws an error
This is just a thought, that might not work at all.这只是一个想法,可能根本行不通。 Or maybe there's a solution without the with statement.
或者也许有一个没有 with 语句的解决方案。
This answers the original question but I suggest don't use it .这回答了最初的问题,但我建议不要使用它。
Similar to the suggested way of wKavey .类似于wKavey的建议方式。
But I'm not sure why I would want to do that.但我不确定我为什么要这样做。 I would need to make sure that there is no variable
methodA
in the global namespace.我需要确保全局命名空间中没有变量
methodA
。
class Bar():
def __init__(self, value=5):
self.value = value
def methodA(self):
return self.value
def methodB(self):
return -self.value
def __enter__(self):
global methodA
global methodB
methodA = self.methodA
methodB = self.methodB
def __exit__(self, *args):
global methodA
del methodA
global methodB
del methodB
pass
foo = Bar()
with foo:
print(methodA()) # all works fine
print(methodB())
methodA() # throws an error
You can probably use the techniques described here: Insert variable into global namespace from within a function?您可能可以使用此处描述的技术: 从函数内将变量插入全局命名空间?
I'd imagine it will require some bookkeeping in the __enter__
and __exit__
functions in order to clean up after itself.我想它需要在
__enter__
和__exit__
函数中进行一些簿记,以便在其之后进行清理。 This isn't really something standard, so there my be some other foot-guns that I'm overlooking.这真的不是标准的东西,所以我有一些其他的脚踏枪我忽略了。
(oh. Maximilian Peters' answer is doing the same with slightly different syntax and was here first...) (哦。Maximilian Peters 的回答是用略有不同的语法做同样的事情,并且首先出现在这里......)
nothing i'd recommend but you could do this (you get in trouble of course if there is already a methodA
in the global namespace):我没有什么建议,但你可以这样做(如果全局命名空间中已经有一个
methodA
,你当然会遇到麻烦):
class Bar():
def methodA(self):
print("methodA called")
def methodB(self):
print("methodB called")
def __enter__(self):
g = globals()
g["methodA"] = self.methodA
g["methodB"] = self.methodB
def __exit__(self, *args):
g = globals()
del g["methodA"]
del g["methodB"]
foo = Bar()
with foo:
methodA() # all works fine
methodB()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.