Let us suppose the following situation: I have a class with some initial values. Furthermore, I want to provide the possibility to pass an user-defined method, when initializing a new object. The user knows about the attributes of the class in advance and may want to consider them in the function, for instance:
class some_class():
def __init__(self, some_method):
# some initial values
self.a = 8
self.b = 12
# initializing a new object with a user-specific method
self.some_method = some_method
def some_method(self):
pass # this method shall be specified by the user
# user-specific function
def some_function():
return self.a + self.b
some_object = some_class(some_method = some_function)
print(some_object.some_method())
Of course, the given example does not work, but I hope it shows what I want to do. I am searching for a way to define a function outside the class, which refers to the attribute of an object after it was passed during initialization.
What I try to avoid is to solve the problem with fixed name conventions, for instance:
class some_class():
def __init__(self, some_method):
self.a = 8
self.b = 12
self.some_method = some_method
def some_method(self):
pass
def some_function():
return some_object.a + some_object.b # -> fixed names to avoid the problem
some_object = some_class(some_method = some_function)
print(some_object.some_method())
I think what I need is a kind of placeholder or alternative to self. Does anybody has an idea?