【问题标题】:How to assign a __call__ method to a module/package?如何将 __call__ 方法分配给模块/包?
【发布时间】:2021-05-19 19:57:03
【问题描述】:

这可能是一个愚蠢的问题,但我在 SO 上进行了一些谷歌搜索和挖掘,但没有找到正确的答案。所以我只想问:

是否可以将 __call__ 方法分配给 Python 模块或包?

我的意思是,我可以直接调用分配的方法,而不是从模块/包的命名空间调用方法吗?

现在怎么样了:

import foo

foo.bar(123)

我想做什么:

import foo

foo(123)

如果这不可能,那么在这样的功能中进行猴子补丁需要什么? (这可能要求很多)

【问题讨论】:

  • @Carcigenicate 我不需要需要调用模块本身,我只是想知道,因为它在语义上对我更有吸引力。

标签: python methods module


【解决方案1】:

是的,你可以这样做。

foo_module.py

class Foo:
    def __call__(self, arg):
        print(f'Foo({arg!r}) called')

_ref, sys.modules[__name__] = sys.modules[__name__], Foo()

main.py

import foo_module

foo_module(123)  # -> Foo(123) called

【讨论】:

【解决方案2】:

我认为你可以将文件命名为 hello.py 然后这样做:

class hello:
   def hi():
     return "hello"

然后在主文件中做:

from hello import hello
hello.hi()

【讨论】:

  • 虽然我同意这是一个更合理的设置,但这不是他们所追求的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2012-12-02
相关资源
最近更新 更多