有没有一种方法可以进入一个对象的命名空间,以便我可以像使用全局函数一样使用它的方法? 我在考虑使用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 语句。
with
结构在其他语言中也被使用)。我过去也用过它。但我认为这不是一个建议遵循的Python模式。这与在方法内部编写self
有些相关。 - progmatico