簡體   English   中英

為什么會出現AttributeError?

[英]Why I'm getting AttributeError?

我正在使用python( https://github.com/parthanium/YoPy )中的Yo api開發應用程序,但遇到了一個非常奇怪的錯誤。

因此,我將存儲庫克隆到了我的工作區中,並創建了以下文件(test.py),該文件在運行python test.py時可以正常工作:

import yopy

token = "secret"
username = "testUser"
link = "https://github.com/parthanium/YoPy"

yo = yopy.Yo(token)
print yo
print yo.number()

現在的問題是:

我有一個項目,其中包括以前的項目(Python中的Yo api)作為git子模塊:

yo/
├── README.md
├── gitmodules
│   └── yopy
│       ├── LICENSE
│       ├── README.md
│       └── yopy.py
└── yo.py

yo.py文件具有以下內容:

import sys
sys.path.append("gitmodules/yopy")
import yopy
import struct

token = "secret"
username = "testUser"
link = "https://github.com/parthanium/YoPy"

yo = yopy.Yo(token)
print yo
print dir(yo)
print yo.number()

並且在運行時出現以下錯誤輸出:

<yopy.Yo object at 0x10cc29190>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_session', 'token', 'user', 'yo', 'yo_all']
Traceback (most recent call last):
  File "yo.py", line 13, in <module>
    print yo.number()
AttributeError: 'Yo' object has no attribute 'number'

為什么會出現此錯誤? dir(yo)輸出奇怪的屬性,例如'yo_all'和'yo','user'...

編輯:嘗試'打印yopy。 文件 ',結果是https://gist.github.com/pedrorijo91/4fb4defe7a7c2d8a2fdc (感謝@abarnert)

問題幾乎可以肯定是,您的sys.path還有其他名為yopy.pyyopy.pycyopy東西,很可能在您試圖從中運行此文件的當前工作目錄中。 它可能是同一個庫的舊版本,或者是您為測試該庫而編寫的某些測試程序,或者是具有相同名稱的其他項目。

現在,您的sys.path.append("gitmodules/yopy")確實將正確的目錄添加到了導入程序搜索路徑中,但是它在末尾而不是開始處添加了它。 因此,如果有一個./yopy.py以及一個./gitmodules/yopy/yopy.py ,則這是Python要導入的第一個。

您可以通過print yopy.__file__看到導入的print yopy.__file__ 或者,最好import inspect ,然后print inspect.getsourcefile(yopy)

假設這是問題所在,解決方法是擺脫名稱沖突的其他問題。 (您可以改為將sys.path.append(…)更改為sys.path.insert(0, …) ,但是周圍出現其他問題yopy導致更多的混亂……)

暫無
暫無

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

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