【问题标题】:Calling a helper function from inside a class variable从类变量内部调用辅助函数
【发布时间】:2021-10-12 10:17:57
【问题描述】:

考虑以下代码:

# foo.py

class A:
    def _foo():
        print('hello world')
    
    bar = {'foo': _foo}

    def run_bar(self):
        self.bar['foo']()

def main():
    A().run_bar()

if __name__ == '__main__':
    raise SystemExit(main())

它在 Python 3.9.5 上运行得很好:

python3.9 foo.py
> hello world

但是mypywill give me出现以下错误:

mypy foo.py
> foo.py:2: error: Method must have at least one argument
> Found 1 error in 1 file (checked 1 source file)

有没有办法告诉 mypy 这个函数只会作为类变量被调用?如果不是,这是不好的做法吗?我知道我可以简单地添加# type: ignore,但这似乎太老套了。

【问题讨论】:

  • 应该是def _foo(self):
  • 如果_foo 不是真正的类方法或实例方法,您可以在类之外定义它。
  • 我建议在那里使用静态方法
  • @khelwood,是的,谢谢,这行得通。

标签: python python-3.x type-hinting mypy python-typing


【解决方案1】:

两种方法:

1.使用staticmethod

像这样:

from typing import Callable, Any

class A:
    bar: dict[str, Callable[..., Any]] = {}

    def __init__(self):
        self.bar.update({'foo': self._foo})

    @staticmethod
    def _foo():
        print('hello world')

    def run_bar(self):
        self.bar['foo']()
    

def main():
    A().run_bar()
  

if __name__ == '__main__':
    raise SystemExit(main())

或者像这样:

class A:
    @staticmethod
    def _foo():
        print('hello world')
 
    def run_bar(self):
        getattr(self, '_foo')()
        

def main():
    A().run_bar()


if __name__ == '__main__':
    raise SystemExit(main())

2。将函数放在类之外

def _foo():
    print('hello world')


class A:
    bar = {'foo': _foo}
   
    def run_bar(self):
        self.bar['foo']()
    

def main():
    A().run_bar()
  

if __name__ == '__main__':
    raise SystemExit(main())

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2013-08-22
    • 1970-01-01
    • 2019-08-02
    • 2011-03-27
    相关资源
    最近更新 更多