【问题标题】:What use is there for defining magic methods outside of a class?在类之外定义魔术方法有什么用?
【发布时间】:2020-12-16 16:40:00
【问题描述】:

如果我在类之外定义一个魔术方法会发生什么?
例如,假设我愿意:

def __str__(stuff):
    return "chicken"

直接在模块内部。

这样的东西什么时候有用?我认为如果我在其他地方 import 这个模块名为 module1 并尝试执行 print(module1) 可能会很有用,但这只会打印出文件位置和其他内容。

那么在类之外使用魔法方法有什么用吗?真的是神法吗?

【问题讨论】:

    标签: python string class module magic-methods


    【解决方案1】:

    目前(Python 3.9),可以定义两个模块级魔术方法:__getattr____dir__(详见PEP 562)。

    • __getattr__ 覆盖对该模块的属性访问,包括 from x import y 形式的导入。
    • __dir__ 覆盖 dir(module) 返回的内容。

    例如:

    # foo.py
    
    def __getattr__(name):
        return name
    
    def __dir__():
        return ['foo', 'bar']
    

    那么我们可以通过以下方式使用它:

    >>> import foo
    >>> dir(foo)
    ['bar', 'foo']
    >>> from foo import bar
    >>> bar
    'bar'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      相关资源
      最近更新 更多