LoginSignup
5
7

More than 5 years have passed since last update.

Python3で自作モジュール全体を読み込もうとした時の勘違いのメモ

Last updated at Posted at 2016-05-06

何が起こったか

ある自作モジュール(fruits.py)の中にある,複数のclass(Apple, Orange, Grape)をimport fruitsで読み込もうとした時の勘違いをメモ.
参考:http://www.python-izm.com/contents/basis/import.shtml

今回の勘違い

以下のようなモジュールがあるとする.

fruits.py
class Apple():
  def hoge():
    pass

class Orange():
  def hoge():
    pass

class Grape():
  def hoge():
    pass

このモジュール内のクラスをimport fruitsで読み込んで,インスタンスを作成しようとしたところ,以下のエラーが出た.

>>> import fruits
>>> apple = Apple()

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

正しくは,モジュール名.クラスのように扱う.今回の勘違いはimport モジュールtype(クラス名)のように扱おうとしたことが原因だった.

>>> import fruits    
>>> type(fruits.Apple)
<class 'type'>   

もしtype(クラス名)のように扱う場合は,以下のようにする.

>>> from fruit import Apple
>>> type(Apple)
<Class 'type'>

追記

shiracamusさんからコメントを頂きました.
type(クラス)のようにしたい場合は,from モジュール import *と書けば可能です.

>>> from fruit import *
>>> type(Apple)
<class 'type'>
5
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7