python:: *args **kwargs 사용방법

 

간단 설명

*, **가 입력변수 앞에 붙어야 함

# (*args) : 여러개 input
def func1(*args):
    ...

# (**kwargs) : 여러개 key-value , dictionary형태 input
def func2(**kwargs):
    ...

 

 

적용예시1

#### 개별 input
def func1(input1, input2, input3):
    print("arg1:", input1)
    print("arg2:", input2)
    print("arg3:", input3)

func1("myName", "is", "thekkom")



#### *args 사용
def func1(*args):
    print("args:", args)
    for arg in args:
        print(arg)

func1("myName", "is")

func1("myName", "is", "thekkom",)

 

 

적용예시2

## **kwargs 사용시
def func2(**kwargs):
    print(kwargs)
    for key, value in kwargs.items():
        print(f"key = {key}, value = {value}")
	
    print("========")
    print("arg1:", kwargs["arg1"])
    print("arg2:", kwargs["arg2"])
    print("arg3:", kwargs["arg3"])

func2(arg1 ="myName", arg2 ="is", arg3="thekkom",)


# OUTPUT
# {'arg1': 'myName', 'arg2': 'is', 'arg3': 'thekkom'}
# key = arg1, value = myName
# key = arg2, value = is
# key = arg3, value = thekkom
# ========
# arg1: myName
# arg2: is
# arg3: thekkom

 

 

 

 


실제사용 예시

import tkinter
  

root = tkinter.Tk()
root.title("args and kwargs")
root.geometry('700x500')
  
# Create the list of options
options_list = ["Option 1", "Option 2", "Option 3", "Option 4"]
  
value_inside = tkinter.StringVar(root)
value_inside.set("Select an Option")

# option_list에 *args로 사용됨
question_menu = tkinter.OptionMenu(root, value_inside, *options_list)
question_menu.pack()



def print_answers():
    print("Selected Option: {}".format(value_inside.get()))
    return None
  
  
# Submit button
# Whenever we click the submit button, our submitted
# option is printed ---Testing purpose
submit_button = tkinter.Button(root, text='Submit', command=print_answers)
submit_button.pack()
  
root.mainloop()

https://www.geeksforgeeks.org/tkinter-optionmenu-widget/

 

Tkinter - OptionMenu Widget - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

 

 

 

 

 

_

 

반응형