Home > Mobile >  How do you use a function in a class, inside another function?
How do you use a function in a class, inside another function?

Time:10-30

I have a class similar to the one below where I have created some functions measure reliability on a classifier. The last function in the class has to use the return values of the other functions.

class ClassifierAccuracy:

  def __init__(self, list1, list2):

     self.A = list1   list2 
     self.B = list1 - list2
     self.C = list2 - list1


    def add_AB(self):
      add_ab = self.A   self.B
      return add_ab

    def add_AC(self):
       add_ac = 0
       add_ac = self.A   self.C
       return r

    def difference(self):
       diff = 0
       diff = self.add_AC / self.add_AB        # This is the bit of code that fails
       return diff

The problem I've been having is that I can't seem to be able to call function add_AC and add_AB inside function difference. What is the correct syntax to write here?

CodePudding user response:

class ClassifierAccuracy:

def __init__(self, list1, list2):

   self.A = list1   list2 
   self.B = list1 - list2
   self.C = list2 - list1


def add_AB(self):
  add_ab = self.A   self.B
  return add_ab

def add_AC(self):
   add_ac = 0
   add_ac = self.A   self.C
   return add_ac

def difference(self):
   diff = 0
   diff = self.add_AC() / self.add_AB()        # This is the bit of code that fails
   return diff

This code works

CodePudding user response:

You must call the method, not just get the method.

class ClassifierAccuracy:

  def __init__(self, list1, list2):

     self.A = list1   list2 
     self.B = list1 - list2
     self.C = list2 - list1


    def add_AB(self):
      add_ab = self.A   self.B
      return add_ab

    def add_AC(self):
       add_ac = 0
       add_ac = self.A   self.C
       return r

    def difference(self):
       diff = 0
       diff = self.add_AC() / self.add_AB()        
       return diff

This idea can be shown here:

def foo():
    return "foo"

print(foo)
print(foo())

Output:

>>> <function foo at 0x7fb6887379d0>
>>> foo

We get <function foo at 0x7fb6887379d0> because we simply have asked python to retrieve the object, not call it.

Side note: This is the default representation of a function object. It provides you with a name and a unique id.

We then get foo because we've actually called the function, that returned the string foo.

  • Related