繁体   English   中英

在 Python 中输入对象命名空间

[英]Enter object namespace in Python

有没有办法输入对象的命名空间,以便我可以像使用全局方法一样使用它的方法? 我在想一些使用 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

这只是一个想法,可能根本行不通。 或者也许有一个没有 with 语句的解决方案。

这回答了最初的问题,但我建议不要使用它


类似于wKavey的建议方式。

但我不确定我为什么要这样做。 我需要确保全局命名空间中没有变量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

您可能可以使用此处描述的技术: 从函数内将变量插入全局命名空间?

我想它需要在__enter____exit__函数中进行一些簿记,以便在其之后进行清理。 这真的不是标准的东西,所以我有一些其他的脚踏枪我忽略了。

(哦。Maximilian Peters 的回答是用略有不同的语法做同样的事情,并且首先出现在这里......)

我没有什么建议,但你可以这样做(如果全局命名空间中已经有一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM