Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can methods have methods in Python?

this may seem a little odd, but it would make for a convenient way for me to finish a bit of code.

Because Python methods are objects themselves, could a method have a method of its own? That is, if I wanted to do the following (ignoring syntax):

def methodCaller(someArgs, methodB):
    # some stuff here . . .
    variableWithAGoodName = methodB()
    jonSkeet = methodB.methodC(variableWithAGoodName)
    return jonSkeet

Would it be possible? My guess is no, but if methods are just objects, shouldn't it be possible somehow?

Thank you so much!

EDIT: I think as has been posted, I am looking for a high-order function.

My question is somewhat academic as I know I could reorganize my code to do this manner of thing totally differently. But, as it is, I am experimenting with Python to learn at least its basics. I haven't tried this yet, but as I am unfamiliar with Python, it might be possible, just not with this syntax.

Another EDIT: I attempted to be funny with my naming but it made the question unclear. For that I apologize. Here is a better example:

def MethodA(MethodB):
    # MethodB is passed as a parameter but is also a method.
    # MethodB has a method of its own, somehow, because it is technically still
    # an object.
    MethodB.MethodC() #Let's pretend it returns nothing here.
    # Can this happen?
like image 708
BlackVegetable Avatar asked Dec 28 '22 05:12

BlackVegetable


1 Answers

Functions in python are first-class objects with methods and attributes.

def foo():
    print("foo")

def bar():
    print("bar")

foo.bar = bar
foo.bar()                  #outputs "bar"

foo.baz = "Hello, world!"
print(foo.baz)             # outputs "Hello, World!"

Edit:

Because functions are first-class objects, you can also pass them around like any other variable. You can also write "higher-order functions", which are functions of functions (or functions that return functions.)

Edit 2:

[To the tune of 'There ain't no party like an S-Club party!'] There ain't no example like a full-code example!

def higher_order_function (input_function):
    input_function.method()

def input_function_1 ():
    print ("exec'ing input_function_1()")

def input_function_1_method ():
    print ("exec'ing input_function_1_method()")

input_function_1.method = input_function_1_method

higher_order_function(input_function_1)
# prints "exec'ing input_function_1_method"
like image 89
Li-aung Yip Avatar answered Dec 31 '22 14:12

Li-aung Yip