[Python] Pythone에서 Class, Method, Member Variable 사용하기
Python에서 Class 을 사용할 수 있으며, public, private, protected 등을 통해 정보 은닉 기능을 제공한다.
1. Class 선언
Python에서 클래스 선언과 사용은 쉽다.
아래 예제는 ','로 구분되어진 텍스트 파일에서 각 항목별로 데이터가 중복되지 않고 어떤 항목들이 있는지를 찾아내는 프로그램이다. 예제에서는 FileDataConverter, ItemInfo 등 두 개의 class을 선언하고, 각 class 안에 멤버 변수와 메소드를 정의하여 사용하였다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 각 컬럼별 항목을 분리할 리스트 | |
class ItemInfo: | |
index_ = -1 | |
itemList_ = [] | |
def __init__(self, index): | |
self.index_ = index | |
self.itemList_ = [] | |
def isExistItem(self, find_string): | |
for item in self.itemList_: | |
if find_string == item: | |
return True | |
return False | |
def appendItem(self, new_string): | |
if self.isExistItem(new_string) == True: | |
return False | |
self.itemList_.append(new_string) | |
return True | |
def showItems(self): | |
for item in self.itemList_: | |
print (item) | |
# 파일 변환기 | |
class FileDataConverter: | |
inputFilename_ = "" | |
outputFilename_ = "" | |
itemInfos_ = [] | |
def __init__(self, inputFilename, outputFilename): | |
self.inputFilename_ = inputFilename | |
self.outputFilename_ = outputFilename | |
self.itemInfos_ = [] | |
def getItemInfo(self, index): | |
for itemInfo in self.itemInfos_: | |
if itemInfo.index_ == index: | |
return itemInfo | |
return None | |
def showItemInfos(self): | |
for itemInfo in self.itemInfos_: | |
print("#####", itemInfo.index_, "########") | |
itemInfo.showItems() | |
def analysis(self): | |
isFirstLine = True | |
# 파일에서 line 별로 데이터를 읽어 드림 | |
for line in open(self.inputFilename_): | |
# 첫 번째 라인은 타이틀이기 때문에 제외 | |
if isFirstLine is True: | |
isFirstLine = False | |
continue | |
# split the text | |
words = line.rstrip('\n').split(",") | |
# for each word in the line: | |
for index, word in enumerate(words): | |
# 숫자가 아닌 경우에는 아이템의 인덱스별로 데이터를 추가함 | |
if word.isdigit() != True: | |
itemInfo = self.getItemInfo(index) | |
if itemInfo is None: | |
newItemInfo = ItemInfo(index) | |
self.itemInfos_.append(newItemInfo) | |
itemInfo = newItemInfo | |
itemInfo.appendItem(word) | |
# print the word | |
# print(index, word) | |
self.showItemInfos() | |
# 각 항목별 리스트를 정리 | |
x = FileDataConverter("train.csv", "converted_train.csv") | |
x.analysis() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 각 컬럼별 항목을 분리할 리스트 | |
class ItemInfo: | |
index_ = -1 | |
itemList_ = [] | |
def __init__(self, index): | |
self.index_ = index | |
self.itemList_ = [] | |
def isExistItem(self, find_string): | |
for item in self.itemList_: | |
if find_string == item: | |
return True | |
return False | |
def appendItem(self, new_string): | |
if self.isExistItem(new_string) == True: | |
return False | |
self.itemList_.append(new_string) | |
return True | |
def showItems(self): | |
for item in self.itemList_: | |
print (item) | |
# 파일 변환기 | |
class FileDataConverter: | |
inputFilename_ = "" | |
outputFilename_ = "" | |
itemInfos_ = [] | |
def __init__(self, inputFilename, outputFilename): | |
self.inputFilename_ = inputFilename | |
self.outputFilename_ = outputFilename | |
self.itemInfos_ = [] | |
def getItemInfo(self, index): | |
for itemInfo in self.itemInfos_: | |
if itemInfo.index_ == index: | |
return itemInfo | |
return None | |
def showItemInfos(self): | |
for itemInfo in self.itemInfos_: | |
print("#####", itemInfo.index_, "########") | |
itemInfo.showItems() | |
def analysis(self): | |
isFirstLine = True | |
# 파일에서 line 별로 데이터를 읽어 드림 | |
for line in open(self.inputFilename_): | |
# 첫 번째 라인은 타이틀이기 때문에 제외 | |
if isFirstLine is True: | |
isFirstLine = False | |
continue | |
# split the text | |
words = line.rstrip('\n').split(",") | |
# for each word in the line: | |
for index, word in enumerate(words): | |
# 숫자가 아닌 경우에는 아이템의 인덱스별로 데이터를 추가함 | |
if word.isdigit() != True: | |
itemInfo = self.getItemInfo(index) | |
if itemInfo is None: | |
newItemInfo = ItemInfo(index) | |
self.itemInfos_.append(newItemInfo) | |
itemInfo = newItemInfo | |
itemInfo.appendItem(word) | |
# print the word | |
# print(index, word) | |
self.showItemInfos() | |
# 각 항목별 리스트를 정리 | |
x = FileDataConverter("train.csv", "converted_train.csv") | |
x.analysis() |
2. Public, Protected(_), Private(__) : 접근 제어(정보 은닉)
Python은 기본적으로 Class 내에 메소드나 멤버 변수를 선언하는 키워드는 없다. 메소드나 멤버변수 이름 앞에 다음과 같은 prefix 들 추가하면 된다.
- '': public
- prefix가 없다면 모든 것은 public
- '_' : protected
- 이름 앞에 '_' 을 추가하면 protected 로 선언
- '__'
- 이름 앞에 '__'를 추가하면 private로 선언
위 예제에서 일부 멤버 변수와 메소드에 접근 제어를 한 수정된 코드는 다음과 같다.
C++나 Java를 사용했던 사람들은 조금 어색할 수 있지만, 개인적으로 명확하고 깔끔한 선언 방법으로 느껴지다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 각 컬럼별 항목을 분리할 리스트 | |
class ItemInfo: | |
index = -1 # public variable | |
itemList = [] # public variable | |
def __init__(self, index): | |
self.index = index | |
self.itemList = [] | |
def __isExistItem(self, find_string): # private method | |
for item in self.itemList: | |
if find_string == item: | |
return True | |
return False | |
def appendItem(self, new_string): | |
if self.__isExistItem(new_string) == True: | |
return False | |
self.itemList.append(new_string) | |
return True | |
def showItems(self): | |
for item in self.itemList: | |
print (item) | |
# 파일 변환기 | |
class FileDataConverter: | |
_inputFilename = "" # protected variable | |
_outputFilename = "" # protected variable | |
_itemInfos = [] # protected variable | |
def __init__(self, inputFilename, outputFilename): | |
self._inputFilename = inputFilename | |
self._outputFilename = outputFilename | |
self._itemInfos = [] | |
def __getItemInfo(self, index): # private variable | |
for itemInfo in self._itemInfos: | |
if itemInfo.index == index: | |
return itemInfo | |
return None | |
def showItemInfos(self): | |
for itemInfo in self._itemInfos: | |
print("#####", itemInfo.index, "########") | |
itemInfo.showItems() | |
def analysis(self): | |
isFirstLine = True | |
# 파일에서 line 별로 데이터를 읽어 드림 | |
for line in open(self._inputFilename): | |
# 첫 번째 라인은 타이틀이기 때문에 제외 | |
if isFirstLine is True: | |
isFirstLine = False | |
continue | |
# split the text | |
words = line.rstrip('\n').split(",") | |
# for each word in the line: | |
for index, word in enumerate(words): | |
# 숫자가 아닌 경우에는 아이템의 인덱스별로 데이터를 추가함 | |
if word.isdigit() != True: | |
itemInfo = self.__getItemInfo(index) | |
if itemInfo is None: | |
newItemInfo = ItemInfo(index) | |
self._itemInfos.append(newItemInfo) | |
itemInfo = newItemInfo | |
itemInfo.appendItem(word) | |
self.showItemInfos() | |
# 각 항목별 리스트를 정리 | |
x = FileDataConverter("train.csv", "converted_train.csv") | |
x.analysis() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 각 컬럼별 항목을 분리할 리스트 | |
class ItemInfo: | |
index = -1 # public variable | |
itemList = [] # public variable | |
def __init__(self, index): | |
self.index = index | |
self.itemList = [] | |
def __isExistItem(self, find_string): # private method | |
for item in self.itemList: | |
if find_string == item: | |
return True | |
return False | |
def appendItem(self, new_string): | |
if self.__isExistItem(new_string) == True: | |
return False | |
self.itemList.append(new_string) | |
return True | |
def showItems(self): | |
for item in self.itemList: | |
print (item) | |
# 파일 변환기 | |
class FileDataConverter: | |
_inputFilename = "" # protected variable | |
_outputFilename = "" # protected variable | |
_itemInfos = [] # protected variable | |
def __init__(self, inputFilename, outputFilename): | |
self._inputFilename = inputFilename | |
self._outputFilename = outputFilename | |
self._itemInfos = [] | |
def __getItemInfo(self, index): # private variable | |
for itemInfo in self._itemInfos: | |
if itemInfo.index == index: | |
return itemInfo | |
return None | |
def showItemInfos(self): | |
for itemInfo in self._itemInfos: | |
print("#####", itemInfo.index, "########") | |
itemInfo.showItems() | |
def analysis(self): | |
isFirstLine = True | |
# 파일에서 line 별로 데이터를 읽어 드림 | |
for line in open(self._inputFilename): | |
# 첫 번째 라인은 타이틀이기 때문에 제외 | |
if isFirstLine is True: | |
isFirstLine = False | |
continue | |
# split the text | |
words = line.rstrip('\n').split(",") | |
# for each word in the line: | |
for index, word in enumerate(words): | |
# 숫자가 아닌 경우에는 아이템의 인덱스별로 데이터를 추가함 | |
if word.isdigit() != True: | |
itemInfo = self.__getItemInfo(index) | |
if itemInfo is None: | |
newItemInfo = ItemInfo(index) | |
self._itemInfos.append(newItemInfo) | |
itemInfo = newItemInfo | |
itemInfo.appendItem(word) | |
self.showItemInfos() | |
# 각 항목별 리스트를 정리 | |
x = FileDataConverter("train.csv", "converted_train.csv") | |
x.analysis() |
3. 참조
- Python Software Foundation / Documentation : https://docs.python.org/2/tutorial/classes.html
댓글
댓글 쓰기