I want to have a function pointer in my class Point.
class Point:
coord=[]
def value(self,p_coord:list=coord):
return abs(self.val(p_coord))
def __init__(self,p_coord:list,p_val):
self.coord=p_coord
self.val=p_val
I'm trying to pass a function pointer to the field "val", But when I try to call the function with the method value(), it returns 0:
def length(par:list):
return len(par)
v1=Point([1, 2, 3],length)
print(v1.value())
How to pass a function to a class field?
The default value coord
in value
is the class attribute from line 2 which is not the same as the instance attribute self.coord
set in __init__
. So the function pointer is working correctly, its just looking at the wrong list.
What you can instead do is:
def value(self, p_coord=None):
if not p_coord:
p_coord = self.coord
return abs(self.val(p_coord))