클래스, Exception, with 구문
기본적으로 파이썬에서는 메서드와 속성 모두 public
class 클래스이름:
def __init__(self,인수,...): #생성자
def 메서드이름(self,인수...): #메서드
클래스변수(C++에서의 static변수)
class Person:
count = 0
def __init__(self,name,name2):
self.name = name
self.__name = name2 #private 멤버
Person.count += 1
print(self.name + " is initialized")
def work(self, company):
print(self.name + " is working in " + company)
def sleep(self):
print(self.name + " is sleeping")
@classmethod
def getCount(cls):
return cls.count
obj1 = Person("PARK")
obj2 = Person("KIM")
obj1.work("ABCDE")
obj2.sleep()
print("courrent person object is ", obj1.name, ", ", obj2.name)
print("Person count == ", Persion.getCount())
print(Person.count)
------------------------------------------------
def print_name(name):
print('[def] ', name)
class SampleTest:
def __init__(self):
pass #아무것도 안하면 pass
def print_name(self, name):
print('[SampleTest] ', name)
def call_test(self):
print_name('KIM') #전역함수를 호출
self.print_name('KIM') #멤버 함수를 호출
obj = SampleTest()
print_name('LEE')
obj.print_name('LEE')
obj.call_test()
------------------------------------------------
def calc(list_data):
sum = 0
try:
sum = list_data[0] + list_data[1] + list_data[2]
if sum < 0
raise Exception("Sum is minus")
except IndexError as err:
print(str(err))
except Exception as err:
print(str(err))
finally:
print(sum)
calc([1,2])
calc([1,2,-100])
------------------------------------------------
#파일 또는 세션 사용 순서 : open > read/write > close
f = open("./file_test", "w")
f.write("Hello, Python !!!")
f.close()
#with를 쓰면 close를 자동으로 해준다.
with open("./file_test", "w") as f:
f.write("Hello, Python !!!")