Python 模块和类 - AttributeError: 模块没有属性

Ear*_*arl 5 python module class

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

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

AttributeError: module 'mystuff' has no attribute 'Piano'
Run Code Online (Sandbox Code Playgroud)

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

ImportError: cannot import name 'Piano'
Run Code Online (Sandbox Code Playgroud)

有人可以解释发生了什么吗?如何在 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)
Run Code Online (Sandbox Code Playgroud)

测试文件

import mystuff 
from mystuff import Piano 
cfcpiano = mystuff.Piano()
cfcpiano.printdetails()
Run Code Online (Sandbox Code Playgroud)

Kaj*_*jal 1

如果你想创建一个名为mystuff

  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
Run Code Online (Sandbox Code Playgroud)
  1. 将您的类复制mystuff.py到文件夹中mystuff
  2. test.py在文件夹(模块)外部创建文件mystuff
#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()
Run Code Online (Sandbox Code Playgroud)

  • `mystuff.py` 不是一个类,而是一个模块。你所描述的(里面有`__init__.py`的文件夹)不是一个模块,而是一个包。您不需要它来创建 python 模块。 (2认同)