I'm new to python and I'm trying to create a module and class.
If I try to import mystuff
and then use cfcpiano = mystuff.Piano()
, I get an error:
AttributeError: module 'mystuff' has no attribute 'Piano'
If I try from mystuff import Piano
I get:
ImportError: cannot import name 'Piano'
Can someone explain what is going on? How do I use a module and class in 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()
If you want to create a python module named mystuff
mystuff
__init__.py
file#__init__.py
from mystuff import Piano #import the class from file mystuff
from mystuff import timesfour,printhello #Import the methods
mystuff.py
to the folder mystuff
test.py
outside the folder(module) mystuff
.#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With