Search code examples
pythonfunctionlambdacallinit

Best way to make variables in init refer to a function's return


I m trying to pass some arguments through the init variables (into class Cat that is inherited in class Dog).

What i want to do is: whenever methods in Cat use the self.dynamic variable they call the function. Instead, with this code, it just sends the result from the first function call.

(wrong example)

class Dog(object):

    def __init__(self):
        self.var = None
        self.dynamic = self.function()

    def change_var(self):
        self.var = 'something'
        print 'var has something'

    def function(self):
        if self.var:

            return 'full'
        else:
            return 'empty'

    def final_function(self):
        return 'it is ' + self.dynamic

my_instance = Dog()

print my_instance.dynamic
>>>empty       # as it should

my_instance.change_var()
>>>var has something   # as it should

print my_instance.final_function()
>>>it is empty    # it didnt update since 'self.var' has the first value stored

I found a solution by using lambda, but i m not sure this is the best way to do it.

class Dog(object):

def __init__(self):
    self.var = None
    self.dynamic = lambda: self.function()

def change_var(self):
    self.var = 'something'
    print 'var has something'

def function(self):
    if self.var:

        return 'full'
    else:
        return 'empty'

def final_function(self):
    return 'it is ' + self.dynamic()

my_instance = Dog()

print my_instance.dynamic()
>>>empty   # as it should
my_instance.change_var() 
>>>var has something   
print my_instance.final_function()
>>>it is full  # it works!! 

Is there a better way to do the above?

PS: Not sure if i use the correct words to describe things, but i m new to programming (and Python).


Solution

  • You don't need the lambda. Functions and methods are already first class objects, and can be assigned to variables:

    self.dynamic = self.function
    

    Although I must say I don't know what either of these are giving you over just calling self.function directly.