簡體   English   中英

導入類時為什么會出現Name Error?

[英]Why am I getting Name Error when importing a class?

我剛剛開始學習Python,但我已經遇到了一些錯誤。 我創建了一個名為pythontest.py的文件,其中包含以下內容:

class Fridge:
    """This class implements a fridge where ingredients can be added and removed individually
       or in groups"""
    def __init__(self, items={}):
        """Optionally pass in an initial dictionary of items"""
        if type(items) != type({}):
            raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
        self.items = items
        return

我想在交互式終端中創建一個新的類實例,所以我在終端中運行以下命令:python3

>> import pythontest
>> f = Fridge()

我收到此錯誤:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Fridge' is not defined

交互式控制台找不到我制作的課程。 但導入成功。 沒有錯誤。

似乎沒有人提到你能做到的

from pythontest import Fridge

這樣,您現在可以直接在命名空間中調用Fridge() ,而無需使用通配符進行導入

你需要這樣做:

>>> import pythontest
>>> f = pythontest.Fridge()

額外獎勵:你的代碼寫得更好:

def __init__(self, items=None):
    """Optionally pass in an initial dictionary of items"""
    if items is None:
         items = {}
    if not isinstance(items, dict):
        raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
    self.items = items

嘗試

import pythontest
f=pythontest.Fridge()

import pythontest ,變量名pythontest將添加到全局命名空間,並且是對模塊pythontest的引用。 要訪問pythontest命名空間中的對象,必須在其名稱前加上pythontest后跟句點。

import pythontest是導入模塊和訪問模塊內對象的首選方法。

from pythontest import *

應該(幾乎)總是避免。 我認為可以接受的唯一時間是在包的__init__設置變量,以及在交互式會話中工作時。 應該避免使用from pythontest import *的原因之一是它很難知道變量的來源。 這使得調試和維護代碼更加困難。 它也不協助模擬和單元測試。 import pythontestpythontest了自己的命名空間。 正如Python的禪宗所說,“命名空間是一個很棒的主意 - 讓我們做更多的事情吧!”

您應該導入名稱,即

 import pythontest
 f= pythontest.Fridge()

要么,

from pythontest import *
f = Fridge()

暫無
暫無

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

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