Asterisk in python: (*) and (**) - basic 2

Couch Potato·2020년 8월 12일
0

python

목록 보기
2/2
post-thumbnail

GO TO Reference

PREVIOUS SERIES, GO TO Post

Asterisk in function hyperparameter

  • 함수에 주어진 키워드 인수를 사전으로 캡처 가능
In [1]: def tag(tag_name, **attributes): 
   ...:     attribute_list = [f'{name}={value}' for name,value in attributes.items()] 
   ...:     return attribute_list 
   ...: tag('img', height=20)                                                                                 
Out[1]: ['height=20']


In [2]: def tag(tag_name, **attributes): 
   ...:     attribute_list = [f'{name}={value}' for name,value in attributes.items()] 
   ...:     return attribute_list                                            
In [3]: tag("img",height=20, width=40, src='face.jpg')                                                        
Out[3]: ['height=20', 'width=40', 'src=face.jpg']
  • 키워드 hyperparameter가 설정되어야함
In [4]: tag("img", 20)                                                                                        
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-eaebaecce1d7> in <module>
----> 1 tag("img", 20) 
TypeError: tag() takes 1 positional argument but 2 were given


In [5]: tag("img", 20,40)                                                                                     
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-535163ffbbd2> in <module>
----> 1 tag("img", 20,40)

TypeError: tag() takes 1 positional argument but 3 were given

Python 3's f-string (An improved string formatting syntax) reference

previously, %- formatting are less readable, when it comes to longer strings and multiple parameters

How to use

  • Simple usage : "f" or "F" in front of string
In [1]: name = 'Dave'
In [2]: age = 23                        
In [3]: print(f"Hello, I am {name} and {age} years old")
Hello, I am Dave and 23 years old
  • Arbitrary Expressions usage (임의적 표현)
In [1]: def to_lowercase(input): 
   ...:     return input.lower()  
In [2]: name = 'Eric Kim'
In [3]: print(f'Hi, {to_lowercase(name)}')                                                                    
Hi, eric kim 
  • Multiple lines usage:
In [1]: name = "Eric"
In [2]: profession = "comedian"
In [3]: affiliation = "Monty Python"
In [4]: message = (
   ...: f"hi,{name}," 
   ...: f"you are a {profession}" 
   ...: f"you were in {affiliation}")
In [5]: print(message)      
hi,Eric,you are a comedianyou were in Monty Python




0개의 댓글