【问题标题】:Python Module and Class - AttributeError: module has no attributePython 模块和类 - AttributeError:模块没有属性
【发布时间】:2023-04-06 04:23:01
【问题描述】:

我是 python 新手,我正在尝试创建一个模块和类。

如果我尝试导入mystuff,然后使用cfcpiano = mystuff.Piano(),我会收到错误:

AttributeError: module 'mystuff' has no attribute 'Piano'

如果我从mystuff import Piano 尝试,我会得到:

ImportError: cannot import name 'Piano'

有人可以解释发生了什么吗?如何在 Python 中使用模块和类

mystuff.py

def printhello():
    print ("hello")

def timesfour(input):
    print (input * 4)


class Piano:
    def __init__(self):
        self.type = raw_input("What type of piano? ")

    def printdetails(self):
        print (self.type, "piano, " + self.age)

Test.py

import mystuff 
from mystuff import Piano 
cfcpiano = mystuff.Piano()
cfcpiano.printdetails()

【问题讨论】:

  • mystuff 目录中有__init__.py 文件吗?
  • 我们可以查看您的完整文件层次结构吗?
  • Test.pymystuff.py 必须在同一个文件夹中,您的代码才能正常工作。
  • 这是一个很长的镜头..但是从您的文件夹中删除所有 .pyc 文件
  • 我没有 init 文件,我使用 Anaconda,创建了一个项目,然后添加了一个模块。

标签: python class module


【解决方案1】:

如果你想创建一个名为mystuff的python模块

  1. 创建一个名为mystuff的文件夹
  2. 创建__init__.py 文件
    #__init__.py from mystuff import Piano #import the class from file mystuff from mystuff import timesfour,printhello #Import the methods

  3. 将你的班级mystuff.py复制到文件夹mystuff

  4. 在文件夹(模块)mystuff 之外创建文件test.py#test.py from mystuff import Piano cfcpiano = Piano() cfcpiano.printdetails()

这会奏效。

【讨论】:

  • mystuff.py 不是一个类,而是一个 moule。你描述的(里面有__init__.py的文件夹)不是一个模块,而是一个包。你不需要它来创建一个 python 模块。
  • 谢谢,我尝试了该文件夹,但找不到该模块。我将所有没有 Init 页面的代码页放在一个项目下,它似乎可以工作。两个问题,初始化页面是如何被触发的?它似乎缓存了自己的数据代码 - 例如。如果我将问题更改为钢琴的年龄是多少?这不出现,如何重置这个?谢谢你们的帮助。
猜你喜欢
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 2020-01-01
  • 2018-06-16
  • 2015-03-09
  • 2020-10-18
  • 2016-12-26
  • 2016-04-10
相关资源
最近更新 更多