Tuesday 5 September 2017

Function pointer in C to Python

int calculate(int (*func)(int c), int a, int b)
{
        return (*func)(a+b);
}
 
And in Python the following will look like this
def calculate(func, a, b): 
 return func(a+b);


=====================

#!/usr/bin/python

def square(i):
        result = i;
        for x in range(i-1):
                result *= i

        return result

def calculate(func, a, b):
        return func(a+b);

def main():
        print calculate(square, 1, 1)

if __name__ == "__main__":
    main()

 ===========
 
Strings and Numbers are Immutable and those values can not be changes.
But, List,Dict and tuples are mutable...
  1. the parameter passed in is actually a reference to an object (but the reference is passed by value)
  2. some data types are mutable, but others aren't
So:
  • If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.
  • If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.
 -------------------------
 
def try_to_change_string_reference(the_string):
    print('got', the_string)
    the_string = 'In a kingdom by the sea'
    print('set to', the_string)

outer_string = 'It was many and many a year ago'

print('before, outer_string =', outer_string)#It was many and many a year ago
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)#It was many and many a year ago 

No comments:

Post a Comment