
함수
함수
변수는 Value의 이름표, 함수는 code의 이름표
함수이름은 함수 객체를 바인딩함
def hello():
print('hello')
f = hello
f()
함수의 ()는 호출
class Func:
def __ call__(self):
print('호출됨')
f = Func()
f()
호출됨
위치인자
def print_number(a, b, c):
print(a, b, c)
print_number(7, 8, 9)
7 8 9
def print_number(a, b, c):
print(a, b, c)
print_number(*(7, 8, 9))
7 8 9
가변인자 - 위치가변인자
def foo(*args):
print(args)
foo(1, 2, 3)
foo(1, 2, 3, 4)
(1, 2, 3)
(1, 2, 3, 4)
가변인자 - 키워드가변인자
def foo(**kwargs):
print(kwargs)
foo(a=1, b=2, c=3)
{'a': 1, 'b': 2, 'c': 3}
람다 함수(lambda 함수)
단일문으로 표현되는 익명험수
코드상에서 한번만 사용되는 기능이 있을 때, 굳이 함수로 만들지 않고 일회성으로 만들어 사용
def mul5(x):
return 5*x
a = lambda x: 5*x
print(a(2))
10
함수안의 함수
def outer():
def inner():
print('inner')
return inner
f = outer()
f()
inner
LEGB
L : Local의 약자로 함수 안
E : Enclosed function local:의 약자로 내부함수에서 자신의 외부 함수의 범위를 타냄
G : Global의 약자로 모듈 범위
B : Built - in 파이썬 내장함수
def test():
print(a) # G
test()
20
def outer():
def inner():
print('inner')
return inner
f = outer()
f()
10
a = 10
def test():
a = 20
print(a)
test()
print(a)
20
10
Enclosed Function Locals
def outer():
num = 3 # E
def inner():
print(num)
return inner
f = outer()
f()
3
클로저(Closure)
class outer:
def __init__(self,num):
self.num = num
def __call__(self):
print(self.num)
f1 = outer(3)
f1()
f1 = outer(3)은outer클래스의 인스턴스를 생성합니다.
f1()을 호출하려면outer클래스에__call__()메서드를 정의해야 합니다.
__call__()메서드는 인스턴스를 함수처럼 호출할 수 있게 해주는 메서드입니다.
클래스
클래스
class Person:
pass
p1 = Person()
p2 = Person()
p1.balance = 1000
p2.balance = 100
이 코드에서는 Person이라는 빈 클래스를 정의한 후, 그 클래스로 두 개의 객체 p1과 p2를 생성하고 각각의 객체에 balance라는 속성을 추가함
생성자(Initalization)
class Person:
def __init__(self):
print("태어남..")
p = Person
instance
class Test:
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print(self.name, ',', self.age)
def test_func(self):
self.print_info()
a = Test('kim', 22)
a.print_info()
a.test_func()