簡體   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