Solomon Bbaale Solomon Bbaale - 2 months ago 10
Python Question

What does defining a function with in the __init__ constructor in python mean?

I have just seen this code and would like to know what the function with in the

__init__
function actually means

def __init__(self):
def program(percept):
return raw_input('Percept=%s; action? ' % percept)
self.program = program
self.alive = True

Answer

This code

class Foo:
    def __init__(self):
        def program(percept): 
            return raw_input('Percept=%s; action? ' % percept)
        self.program = program

AFAIK, is actually the exact same as this since self.program = program.

class Foo:
    def __init__(self):
        pass

    def program(self, percept): 
        return raw_input('Percept=%s; action? ' % percept)

The only reason I can see to nest a function there was if you just used the function to do some initializations within the constructor, but didn't want to expose it on the class.