1

I'm trying to call a function from a class in python. This is my code:

class JCMT:
    def be(self):
       if self > 330000:
         return 0.64
       else:
         return 0.69
    def bs(self):
       if self > 330000:
         return 14
       else:
         return 20 

f = 220258

print JCMT.bs(f) 

I'm getting an error of TypeError: unbound method bs() must be called with JCMT instance as first argument (got int instance instead)

Could someone tell me where I'm going wrong?

3 Answers 3

5

Add a static method decorator right above the function to denote a static function called on the class:

@staticmethod 

Problem is your self parameter corresponds to an instance object which is implicitly passed during function invocation and thus an error is thrown when a class is supplied instead. You must remove the self argument and use an argument to denote the numerical argument.

Sign up to request clarification or add additional context in comments.

3 Comments

this is also a great answer :)
This is the right way. On top, I would rename the argument from self to something else so as to avoid confusion with regular instance methods.
It's quite possible that this was supposed to be a regular instance method, and the OP simply forgot (or is unaware of how) to instantiate an object.
5

There were a few problems, I addressed them with comments:

class JCMT:

    # Add parameter
    def bs(self, n):
       if n > 330000:
         return 14
       else:
         return 20

f = 220258

# Make a new instance
j = JCMT()

# Call now, and pass variable
print j.bs(f)

The self part in the method signature is unique. You can read more about it in this answer.

Comments

0

Althout the @staticmethod decorator already provided in an answer solves this particular problem, if in the future you wish to use the class method and retain self, you can also use the @classmethod decorator to call the method directly without instantiating the class first.

class JCMT:
    @classmethod
    def be(self, n):
        if n > 330000:
            return 0.64
        else:
            return 0.69
    @classmethod
    def bs(self, n):
        if n > 330000:
            return 14
        else:
            return 20 

f = 220258

print JCMT.bs(f)
20

Comments

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.