생성자(_init_)이해 및 사용하기(10:12)
# Person instance 생성
class Person:
# 객체를 생성할 때, init 함수 호출됨
def __init__(self, name, age=10): # init 함수 정의
print(self, ' is generated')
self.name = name
self.age = age
pass
#
lks = Person('Bob', 30)
kkm = Person('Alice', 20)
p3 = Person('lks')
print( type(lks), type(kkm) )
#
#lks.name = 'lks'
#lks.age = 20
print( lks.name, ':', lks.age)
print(p3.name, ':', p3.age)
# 객체 생성과 동시에 외부에서 값 주입
self 키워드의 이해 및 사용하기(7:00)
# self
# 모든 파라미터의 첫번째 파라미터로 동작함
class Person:
# 객체를 생성할 때, init 함수 호출됨
def __init__(self, name, age=10): # init 함수 정의
print('self: ', self)
self.name = name
self.age = age
pass
def sleep(self):
print(self)
print(self.name, '은 잠을 잡니다')
a = Person('Aaron', 20)
b = Person('Bob', 30)
print(a.sleep()) # self는 그 객체 자체
print(b) # self는 그 객체 자체
'''
self: <__main__.Person object at 0x1075a3860>
self: <__main__.Person object at 0x1075a3b38>
<__main__.Person object at 0x1075a3860>
Aaron 은 잠을 잡니다
None
<__main__.Person object at 0x1075a3b38>
'''
- python 모든 method의 첫번째 파라미터
method, static method 정의 및 사용하기(12:28)
- class에서method, static method 정의
# 1. 숫자를 하나 증가
# 2. 숫자를 0으로 초기화
# 3. static method 사용, utility class에서 많이 사용함
class Counter:
def __init__(self):
self.num = 0
def print_current_value(self):
print('현재값: ', self.num)
def increment(self):
self.num += 1
def reset(self):
self.num = 0
c1 = Counter()
print( c1.print_current_value() )
c1.increment()
c1.increment()
print( c1.print_current_value() )
# static method
class Math:
@staticmethod
def add(a,b):
return a + b;
@staticmethod
def multiply(a,b):
return a * b
print ( Math.add(10,20) )
print ( Math.multiply(10,20) )