Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function inside of a function inside of a class in Python

So I'm having a problem with a larger piece of code where I'm getting an error message when I'm calling a function inside of another function that is inside of a class. In the code:

#Test program to solve problems. 

class Foo(object):
    def __init__(self, number):
        self.number = number

    def run(self):
        print "I will now square your number"
        print "Your number squared is: "
        print self.calculate()

    #This squares the number
        def calculate(self):
            return self.number**2


if __name__ == "__main__":
    test = Foo(input("Choose a number: "))
    print test.run()

I raise an "AttributeError: Foohas no attribute calculate", but I don't understand why? Am I calling calculate wrong to throw this error?

EDIT

So I know that if I change the indentation or calculate it works, but I wanna know is there anyway to get it working as it currently is with calculate indented in run or do python classes not work that way.

like image 954
Flameancer Avatar asked Sep 06 '25 09:09

Flameancer


2 Answers

Updated after question edit:

Check out this link that shows how to make a "closure" https://stackoverflow.com/a/4831750/2459730

It's what you described as a function inside of a function.

def run(self):
    def calculate(self): # <------ Need to declare the function before calling
        return self.number**2

    print "I will now square your number"
    print "Your number squared is: "
    print self.calculate() # <---- Call after the function is declared

Before question edit: Your calculate function isn't indented properly.

def run(self):
    print "I will now square your number"
    print "Your number squared is: "
    print self.calculate()

#This squares the number
def calculate(self): # <----- Proper indentation
    return self.number**2 # <------ Proper indentation

The calculate function should have the same indentation level as the run function.

like image 67
Andrew_CS Avatar answered Sep 08 '25 11:09

Andrew_CS


Indentation level is off. You are defining calculate INSIDE of the run function instead of in the class.

class Foo(object):
    def __init__(self, number):
        self.number = number

    def run(self):
        print "I will now square your number"
        print "Your number squared is: "
        print self.calculate()

    #This squares the number
    def calculate(self): #NOTE THE INDENTATION DIFFERENCE
        return self.number**2


if __name__ == "__main__":
    test = Foo(input("Choose a number: "))
    print test.run()
like image 33
Tadgh Avatar answered Sep 08 '25 10:09

Tadgh