简体   繁体   中英

Define Python class member function with *args

In Python how could I define a member function with an unknown number of parameters without using keyword arguments? Something like this:

class Foo:
    def speak(self, *args):
        ...

You can do just that pretty easily. Note that you can iterate through each element in args .

class Foo:
    def speak(self, *args):
        for arg in args:
            print(arg, end=" ")
            
bar = Foo()
bar.speak("Hello", "I", "am", "bar")

Output:

Hello I am bar

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