代码之家  ›  专栏  ›  技术社区  ›  Yaroslav Bulatov

使模块方法像@property一样?

  •  0
  • Yaroslav Bulatov  · 技术社区  · 7 年前

    我有一个模块,我使用的方法如下

    import module
    print(module.location())
    print(module.info2())
    

    print(module.location)
    print(module.info2)
    

    ?

    2 回复  |  直到 7 年前
        1
  •  1
  •   kindall    7 年前

    sys.modules 实际上是一个模块。所以这在技术上是可能的。例如:

    将这些方法定义为属性的类。

    class Module:
        @property
        def location(self):
            return _location
    

    实例化类。

    module = Module()
    

    最后,替换中的模块引用 系统模块 引用实例。

    import sys
    sys.modules[__name__] = module
    

    但是,可以考虑只编写类并在模块中创建一个实例,然后使用以下方法导入它:

    from module import module
    

    很明显你得到了一些东西

        2
  •  1
  •   snakecharmerb    7 年前

    如果您使用Python3.7+,并且控制 module ,您可以创建 __getattr__ 方法打开 模块 部分模仿财产行为。

    def _location():
        return 'here'
    
    
    def _info2():
        return 'Some info'
    
    
    def __getattr__(name):
        if name == 'info2':
            return _info2()
        elif name == 'location':
            return _location()
        raise AttributeError(f'No attribute {name}')
    
    >>> import module
    >>> module.location
    'here'
    >>> module.info2
    'Some info'
    

    但是,没有什么可以阻止显式设置属性,覆盖 :

    >>> module.info2 = 'foo'
    >>> module.info2
    'foo'
    

    __格塔特__ here