Note the misunderstanding when trying to read multiple classes (Apple, Orange, Grape) in a self-made module (fruits.py) with ʻimport fruits`. Reference: http://www.python-izm.com/contents/basis/import.shtml
Suppose you have the following modules.
fruits.py
class Apple():
def hoge():
pass
class Orange():
def hoge():
pass
class Grape():
def hoge():
pass
When I read the class in this module with ʻimport fruits` and tried to create an instance, the following error occurred.
>>> import fruits
>>> apple = Apple()
>>> type(apple)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Apple' is not defined
Correctly, treat it as module name.class
. The cause of this misunderstanding was that I tried to treat it as type (class name)
with the ʻimport module`.
>>> import fruits
>>> type(fruits.Apple)
<class 'type'>
If you want to treat it like type (class name)
, do as follows.
>>> from fruit import Apple
>>> type(Apple)
<Class 'type'>
We received a comment from shiracamus.
If you want to make it like type (class), you can write from module import *
.
>>> from fruit import *
>>> type(Apple)
<class 'type'>
Recommended Posts