Archive

Archive for the ‘python’ Category

Preserving states across function call in Python

Usually functions in Python is not state preserving. That means functions do not save values between calls. But you can make it happen in the following way

 

# this function remember total from last calls
def summation(value):
    summation.total = getattr(summation,"total",0) + value
    return summation.total 

When execute:

summation(1) == 1 # true

summation(2) == 3 # true

summation(3) == 6 # true

 

Saving states across function call might be useful. For example, here I am trying to accumulate sum over a list of numbers.

# clear last total value

summation.total = 0

[summation(x) for x in [1,2,3]] == [1,3,6] # true

 

Advertisements
Categories: python, Uncategorized

Load python script into python command line

execfile(“/path/to/file”)

# Assuming ‘myscript.py’ is in the current directory

execfile(“myscript.py”)

 

Refs:

[1] http://stackoverflow.com/questions/5280178/how-do-i-load-a-file-into-the-python-console

Categories: python, Uncategorized

don’t miss inheriting object when using python @property

Following code looks fine when using python property:

 

class SomeClass():
    @property
    def this( self ):
        return self._hidden_variable * 2
    @this.setter
    def this( self, value ):
        self._hidden_variable = float(value) / 2

 

But the following code would not produce correct result. You must have to inherit object inside SomeClass.

class SomeClass():

has to be changed to

class SomeClass(object):

 

 

 

Categories: python, Uncategorized