简体   繁体   中英

How to make parameter of function act like variable string methods

I want to make function that gets parameter and use it as a method in it. Here is what I'm trying to do with string.upper().lower() methods.

def caps_lock(case, string):
    print(string.case())


string = 'Hello World'

caps_lock(upper, string)
caps_lock(lower, string)

expected result

>HELLO WORLD
>hello world

You could do:

def caps_lock(func, string):
    print(func(string))


string = 'Hello World'

caps_lock(str.upper, string)
caps_lock(str.lower, string)

This is also an option, technically, but I do not recommend it:

def caps_lock(func_name, string):
    print(getattr(string, func_name)())


string = 'Hello World'
caps_lock("upper", string)
caps_lock("lower", string)
def do(obj,method,*params):
    getattr(obj,method)(*params)
    
class Testobj:
    def bla(self,*args):
        print("bla")
        print(args)

do(Testobj(),"bla",1,2,3,4)

#prints: bla (1, 2, 3, 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM