2015년 4월 13일 월요일

python - function


1. 선언

def hello():
    print("hello world!")

hello()



hello world!

2. scope

함수내에서는 local변수로 사용함

외부 변수를 사용하려면 global 로 전역변수로 선언을 해서 사용


3. 기본인수

def hello(name="peter"):
    print("hello %s!" % name)

hello()
hello("jsy")


hello peter!
hello jsy!

※ 기본인수는 마지막 파라미터만 사용가능
ex) def hello( name="preter", age)  : X
     def hello( name, age=20)  : O

4. 키워드 인수

def hello(name, age=20, job=""):
    print("Name is %s " % name)
    print("Age is %d " % age)
    print("Job is %s " % job)

hello("peter")
print("")
hello("peter", 30, "Programer")
print("")
hello("peter", 30)
print("")
hello("peter", age=30)
print("")
hello("peter", job="Programer")
print("")
hello("peter", age=30, job="Programer")



5. VarArgs

def hello( *tups, **dics ):
    for tup in tups:
        print(tup)

    for dic in dics:
        print( "key=%s -> value=%s:" % (dic, dics[dic]))

hello("first", "second", "end", first=1, second=2)



6. DocString

def hello(*tups, **dics):
    """매소드 설명을 적는다.
    :param tups: tuples파라미터 ( args1, args2, args3 ..)    :param dics: dictionary파라미터 ( key1=value1, key2=value2 )    :return:"""    for tup in tups:
        print(tup)
    for dic in dics:
        print("key=%s -> value=%s:" % (dic, dics[dic]))

hello("first", "second", "end", first=1, second=2)
print(hello.__doc__)


댓글 없음: