簡體   English   中英

Python AttributeError:模塊沒有屬性

[英]Python AttributeError: module has no attribute

我有一個 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'。 上面的實現不正確嗎?

  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 ,它解釋了也支持使用字符串文字。 在這里,使用符號將是最合適的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM