Search code examples
pythonclassreturn

Can something returned in one function be called by another class in Python?


I have the following code:

import ch
import re
import sys

def doMath(desIn):
  desOut = desIn+2
  return desOut

class bot(ch.RoomManager):
  def onMessage(self, room, user, message):
    try:
      cmd, args = message.body.split(" ", 1)
    except:
      cmd, args = message.body, ""

    if cmd=="!math":
      doMath(3)
      print(desOut)

I am using ch.py to run a bot in a Chatango chat room. It is designed to perform a certain task when a user sends out a specific message. In this case when a user sends the message of "!math", I would like for it to call the doMath function with an input (desIn), perform the math operation I coded, and then return an output (desOut). In this case, it should return 5. My code runs all the way through, but it does not seem to print the last line that I wrote. Is it possible to return the output into the bot class I have?

By request, why does this not work?

def doMath(desIn):
  desOut = desIn+2
  return desOut

class A:
  doMath(3)
  print(desOut)

Solution

  • Your desOut variable is a local variable to the doMath function, which means it won't be accessible to the onMessage method. If you want your code to actually print the output of your doMath function, you have to either:

    • Save it in a variable. That's useful if you want to use the same value somewhere else in the onMessage function:
    if cmd == '!math':
        math_output = doMath(3)
        print(math_output)
    
    • Just print the returned value directly:
    if cmd == '!math':
        print(doMath(3))
    

    You can read more details in this SO question or even more details here.