【问题标题】:Why I can´t import a class in python?为什么我不能在 python 中导入一个类?
【发布时间】:2016-01-21 09:08:46
【问题描述】:

这是我的文件夹结构:

├── Basic
├── Coche
│   ├── __init.py__
│   ├── coche.py
├── miPrimerCoche.py

我想在 miPrimerCoche 中导入“coche.py”类。 在 coche.py 我有这个:

class Coche:

    def __init__(self, marca, color, caballos):
        self.marca = marca
        self.color = color
        self.caballos = caballos

    def datos(self):
        return "Este coche es un: " + self.marca + \
           " de color: " + self.color + " y con: " + str(self.caballos)    + " caballos"

而且,在 miPrimerCoche 我有这个代码:

from Coche import coche

miMercedes = coche("Toyota", "verde", 50)
print miMercedes.marca
print miMercedes.datos()

然后,当我运行 miPrimerCoche 时,我收到此错误:

Traceback (most recent call last):
  File     "/Users/personalUser/PycharmProjects/untitled/Basic/importar_clase.py",    line 3, in <module>
    miMercedes = coche("Toyota", "verde", 50)
TypeError: 'module' object is not callable

基本是 src 文件夹(它是蓝色的),我能做什么?

我解决了

  miMercedes = coche.Coche(par1, par2, par3...)

但我不知道是否是这样做的好方法。

【问题讨论】:

  • 您是否尝试过导入课程?
  • 不应该是from coche import Coche吗?
  • 我的导入在“miPrimerCoche”的第一行,我调用文件夹(Coche),从文件夹中调用类。不好吗?
  • 试试from Coche.coche import Coche
  • 这很完美,是最好的方法吗?

标签: python


【解决方案1】:

miPrimerCoche.py的角度来看:

  • Coche 是一个模块(文件夹Coche
  • Coche.coche 是一个子模块(文件coche.py
  • Choche.coche.Coche 是子模块 Coche.coche 中的类 Coche

所以你真的想要:

from Coche.coche import Coche

正如错误所指出的,您要导入的 coche 只是(子)模块。

【讨论】:

  • 这就是我要找的!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多