Reputation: 1007
I have defined a of ordered pairs called f
and defined a function applyfunction
that goes through the ordered pairs looking at the first value to compare and when it does match to print the second value.
f = {(1,2),(2,4),(3,6),(4,8)}
def applyfunction (f,x):
for xy in f:
if xy[0]==x:
print(xy[1])
applyfunction(f,3)
The above works just the way I want it to. In the meantime I have seen that in python there are functions that have a dot notation and I think that would be useful here. So my question, how can I rewrite the applyfunction
definition such that I can use the following notation: f.applyfunction(3)
?
Upvotes: 2
Views: 1031
Reputation: 257
Dots are used to access methods of a class using its object name. If you want to access that using dot operator, create an object called f for a class with a method applyfunction. Then you can accomplish your desired task
Upvotes: 1
Reputation: 9207
You can wrap the ordered pairs into a class of your own, which has the method (method == a function inside a class) you mentioned inside of it.
class OrderedPairWrapper():
def __init__(self, op):
self.op = op
def applyfunction (self, x):
for xy in self.op:
if xy[0]==x:
print(xy[1])
f = {(1,2),(2,4),(3,6),(4,8)}
f = OrderedPairWrapper(f)
print(f.applyfunction(3))
# 6
Upvotes: 2