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?

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
h_user
  • 113
  • 1
  • 5

3 Answers3

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.

Community
  • 1
  • 1
Tyler
  • 17,669
  • 10
  • 51
  • 89
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.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • this is also a great answer :) – Joran Beasley Apr 28 '15 at 20:53
  • 2
    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. – honza_p Apr 28 '15 at 20:54
  • 2
    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. – TigerhawkT3 Apr 28 '15 at 20:55
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
ODiogoSilva
  • 2,394
  • 1
  • 19
  • 20