开发者

import file in same dir

开发者 https://www.devze.com 2023-03-18 13:03 出处:网络
Both files are in the same directory. How can I make the Axe class available to main.py ? # axe.py class Axe:

Both files are in the same directory. How can I make the Axe class available to main.py ?

# axe.py
class Axe:
    name = 'Name'
开发者_开发问答

# main.py
import axe
my_axe = Axe()

NameError: "name 'Axe' is not defined"


You either want from axe import Axe, or my_axe = axe.Axe().


Either:

# main.py
import axe
my_axe = axe.Axe()

or:

# main.py
from axe import * # Or "import Axe" to just get Axe and not everything
my_axe = Axe()

The former is preferred, because if two modules have the same name defined, they won't overlap.


If you want to reference the class directly, then @carlpett's answer will work, otherwise you need to reference the class by it's module, i.e:

import axe
my_axe = axe.Axe()


You can do either of the following.

import axe
my_axe = axe.Axe()

Or

from axe import Axe
my_axe = Axe()
0

精彩评论

暂无评论...
验证码 换一张
取 消