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)
如果你想创建一个名为mystuff
mystuff__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)
mystuff.py到文件夹中mystufftest.py在文件夹(模块)外部创建文件mystuff。#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7737 次 |
| 最近记录: |