我对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()发布于 2017-04-04 07:51:16
如果您想创建一个名为mystuff的python模块
mystuff的文件夹__init__.py文件#__init__.py
from mystuff import Piano #import the class from file mystuff
from mystuff import timesfour,printhello #Import the methodsmystuff.py复制到文件夹mystufftest.py之外创建文件mystuff。#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()https://stackoverflow.com/questions/43200000
复制相似问题