【问题标题】:Python AttributeError: module has no attributePython AttributeError:模块没有属性
【发布时间】:2019-02-26 21:48:08
【问题描述】:

我有一个 python 模块文件,其中包含一堆类定义及其方法 sample.py

def abc():
    ...
class Sampler(object):
    def foo(self):
       ...
class Sampler2(object):
     def bar(self):
         ...

现在我想将此文件导入另一个 python 文件并在定义如下函数时使用类型注释:比如 samplers.py

import sample
 class Xyz(object):
      def foobar(self, sampleparam:sample.Sampler)-> int :
            ...

以上是抛出 ​​AttributeError: module 'sample' has no attribute 'Sampler'。上面的实现不正确吗?

【问题讨论】:

    标签: python-3.x attributeerror type-annotation


    【解决方案1】:
      def foobar(self, sample:sample.Sampler)-> int :
    

    AttributeError: 模块 'sample' 没有属性 'Sampler'。

    形参名为sample,但您导入了sample。重命名形参(可能为sample_),或使用以下语法:

    from sample import Sampler
    ...
        def foobar(self, sample: Sampler) -> int:
    

    参见https://www.python.org/dev/peps/pep-0484/#forward-references,它解释了还支持使用字符串文字。在这里,使用符号是最合适的方法。

    【讨论】:

    • 抱歉,示例参数名称选择不当。我已经更新了提供的示例
    猜你喜欢
    • 2018-04-28
    • 2023-04-06
    • 2018-06-16
    • 2015-03-09
    • 2020-10-18
    • 2016-12-26
    • 2016-04-10
    • 2017-04-07
    • 2013-07-05
    相关资源
    最近更新 更多