5

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()
5
  • Do you have an __init__.py file inside mystuff directory? Commented Apr 4, 2017 at 6:42
  • Can we see your complete file hierarchy? Commented Apr 4, 2017 at 6:44
  • Test.py and mystuff.py has to be in the same folder, for your code to work as is. Commented Apr 4, 2017 at 6:48
  • its a long shot .. But delete all the .pyc files from your folder Commented Apr 4, 2017 at 6:53
  • I dont have an init file, Im using Anaconda, created a project and then added a module. Commented Apr 4, 2017 at 11:39

1 Answer 1

1

If you want to create a python module named mystuff

  1. Create a folder with name mystuff
  2. Create an __init__.py file
#__init__.py

from mystuff import Piano #import the class from file mystuff
from mystuff import timesfour,printhello #Import the methods
  1. Copy your class mystuff.py to the folder mystuff
  2. Create file test.py outside the folder(module) mystuff.
#test.py
from mystuff import Piano
cfcpiano = Piano()
cfcpiano.printdetails()
Sign up to request clarification or add additional context in comments.

2 Comments

mystuff.py is not a class but a moule. What you described (the folder with __init__.py inside) is not a module but a package. You don't need that to create a python module.
Thanks, I tried the folder but it just couldn't find the module. I put all the code pages without Init page under one project and it seems to work. Two questions, how does the init page get fired? It seems to cache self data code - eg. If I alter the question to What is the age of the piano? this does not come up , how does one reset this? Thanks for the help guys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.