views:

1597

answers:

7

So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.

class mystuff:
        def average(a,b,c): #get the average of three numbers
                result=a+b+c
                result=result/3
                return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)


File "class.py", line 7, in <module>
    print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)

What's wrong?

+2  A: 

I won't answer this question. Sorry to act like this, but it really won't help you.

Please read the tutorial on the Python website. There is a section on classes, but please read the whole thing. It should only take a few hours at the most.

I shall then be happy to answer any questions you have.

Ali A
Another great resource to learn Python:http://openbookproject.net//thinkCSpy/
Dirk Stoop
Agreed. Stackoverflow is the place you go to after you have done your basic research.
Algorias
I won't down vote it either but I do think it a bit rude.
Unkwntech
At least answer the question and then point to the reference material, answering these kinds of question helps stackoverflow in a certain way, and being an ass turns people away.
Unkwntech
I was trying not to be an ass, and I did even apologize. But you are entitled to your opinion as usual.
Ali A
This answer is +4 -4, so I guess opinions are mixed.
Ali A
+1: too many things wrong to provide a simple "fix this" answer.
S.Lott
+1 for answer, -1 for rudeness. In other words, I didn't vote
Triptych
+6  A: 

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

Ryan
do you mean it should take the argument self?
Josh Smeaton
you can call it however you want. "self" is just a convention.
nosklo
+1  A: 

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

Suraj Barkale
self is not madatory.
Unkwntech
Disagree. What is not mandatory is name of 'self'. But the first argument of Python member function is a reference to an object. Of course you have class and static methods, but for instance methods the rule applies.
Abgan
+5  A: 

From your example, it seems to me you want to use a static method.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.

Roberto Liffredo
Sorry for the downvote, but I think you misinterpreted the question.It seems that stu is new to Python, so directing him to good resources about Python basics is probably better than showing him how to use static methods ;)
Dirk Stoop
On another hand, the explicit usage of "self" in python and wrong beliefs on static methods are quite a common pitfall for people coming from other languages. As many here are pointing documentation and resources, I think there should be at least one "straight" reply. Thanks for the comment!
Roberto Liffredo
-1: Jumping to advanced concepts of staticmethod.
S.Lott
+1 because I didn't know how to define a static method in Python :)
Mark
A: 

You never created an instance.

You've defined average as an instance method, thus, in order to use average you need to create an instance first.

recursive
Sorry f/t downvote; You're absolutely right, but that's not a very helpful answer
Dirk Stoop
+1  A: 

You need to spend a little more time on some fundamentals of object-oriented programming.

This sounds harsh, but it's important.

  • Your class definition is incorrect -- although the syntax happens to be acceptable. The definition is simply wrong.

  • Your use of the class to create an object is entirely missing.

  • Your use of a class to do a calculation is inappropriate. This kind of thing can be done, but it requires the advanced concept of a @staticmehod.

Since your example code is wrong in so many ways, you can't get a tidy "fix this" answer. There are too many things to fix.

You'll need to look at better examples of class definitions. It's not clear what source material you're using to learn from, but whatever book you're reading is either wrong or incomplete.

Please discard whatever book or source you're using and find a better book. Seriously. They've mislead you on how a class definition looks and how it's used.

You might want to look at http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html for a better introduction to classes, objects and Python.

S.Lott
A: 

Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y
    def sum(self):
            return self.x + self.y

 print mystuff.SetVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok
WorldCitizeN