Why am I getting Name Error when importing a class?

前端 未结 4 1021
我在风中等你
我在风中等你 2020-12-18 08:07

I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents:



        
相关标签:
4条回答
  • Try

    import pythontest
    f=pythontest.Fridge()
    

    When you import pythontest, the variable name pythontest is added to the global namespace and is a reference to the module pythontest. To access objects in the pythontest namespace, you must preface their names with pythontest followed by a period.

    import pythontest the preferred way to import modules and access objects within the module.

    from pythontest import *
    

    should (almost) always be avoided. The only times when I think it is acceptable is when setting up variables inside a package's __init__, and when working within an interactive session. Among the reasons why from pythontest import * should be avoided is that it makes it difficult to know where variables came from. This makes debugging and maintaining code harder. It also doesn't assist mocking and unit-testing. import pythontest gives pythontest its own namespace. And as the Zen of Python says, "Namespaces are one honking great idea -- let's do more of those!"

    0 讨论(0)
  • 2020-12-18 08:28

    No one seems to mention that you can do

    from pythontest import Fridge
    

    That way you can now call Fridge() directly in the namespace without importing using the wildcard

    0 讨论(0)
  • 2020-12-18 08:31

    You're supposed to import the names, i.e., either

     import pythontest
     f= pythontest.Fridge()
    

    or,

    from pythontest import *
    f = Fridge()
    
    0 讨论(0)
  • 2020-12-18 08:42

    You need to do:

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

    Bonus: your code would be better written like this:

    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
    
    0 讨论(0)
提交回复
热议问题