Objects, Classes, and Instances in Python

I've written up this class:

class sphere:

    def __init__(self, radius):
        surfaceArea = 4.0 *  pi  * radius ** 2
        volume = 4.0 / 3 *  pi  * radius ** 2

    def getRadius(self):
        return self.radius

    def surfaceArea(self):
        return self.surfaceArea

    def volume(self):
        return self.volume

def main():
    radius = input("Enter the radius of the sphere: ")
    sphere = sphere(getRadius, surfaceArea, volume)
    print sphere.getRadius
    print sphere.surfaceArea
    print sphere.volume

main()

When I run it it says "UnboundLocalError: local variable 'sphere' referenced before assignment"

What have I done wrong?
blackberrycobblerAsked:
Who is Participating?
 
ramromConnect With a Mentor consultant Commented:
Thanks for your reply. I'm glad it might help.

I pondered  sphere = sphere(...). This (by itself) is acceptable, you just no longer have direct access to the class definition.

Please do not hesitiate to ask questions. We are here to help and sometimes we offer something that does not meet your need.
0
 
ramromconsultant Commented:
There are numerous problems.

1 - sphere is a class definition. When you write sphere = sphere(...) you are asking Python to overwrite the class definition with an instance of the class.
so - use a name other than the class name on the left of the assignment. It is a convention to capitalize class names. So you could name the class Sphere then write sphere = Sphere(...)

2 - the __init__ method expects 1 parameter (radius). You are passing 3. Why? And the names you are passing are undefined globals. And the __init__method does not save radius.

3 - pi is undefined.

4 - in the __init__ method you are creating some local variables (surfaceArea and volume) If you want them to be class members you should write self.surfaceArea just as in the surfaceArea method.

5 - You have another name conflict: surfaceArea originally defined as a function will be overwritten by a number.

6 - print sphere.getRadius will give you something like:
<bound method sphere.getRadius of <__main__.sphere instance at 0x00CC7EB8>>

To call a method add() at the end.

Fix that stuff and come back with a new program.
0
 
blackberrycobblerAuthor Commented:
Thanks, ramrom, for the prompt reply.  I am working on it my revision and  I will be back with the results.  
0
 
ramromconsultant Commented:
You accepted an answer, and I'm curious to know how it helped. Do you have a working version of the program to show us?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.