gpt4 book ai didi

Python 模块和类 - AttributeError : module has no attribute

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:51 24 4
gpt4 key购买 nike

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

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

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

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

ImportError: cannot import name 'Piano'

谁能解释一下这是怎么回事?我如何在 Python 中使用模块和类

我的东西.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)

测试.py

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

最佳答案

如果你想创建一个名为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
  1. 将您的类(class) mystuff.py 复制到文件夹 mystuff
  2. 在文件夹(模块)mystuff 之外创建文件 test.py
#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()

关于Python 模块和类 - AttributeError : module has no attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com