2

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)?

3
  • Those are called methods. They are class attributes. When invoked through a class instance, they become bound methods, with the first argument bound to the class instance. So your question is, "Would defining a class help my application?" Commented Aug 22, 2020 at 8:59
  • I think you're asking how you can add the applyfunction function as a method to sets. Don't do that, just use the function. Commented Aug 22, 2020 at 8:59
  • @jonrsharpe I only want this is a one off way to show the idea of going from a set of ordered pairs to a function. Commented Aug 22, 2020 at 9:01

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this sort of thing ("two methods, one of which is __init__") is canonically when to stop writing classes.
@jonrsharpe I think so too, but I also think he just wanted an example to get his head around this dot methods in the first place.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.