이것저것
생성자(Constructor) 본문
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
a = FourCal()
a.setdata(4,2)
print(a.add())
print(a.mul())
print(a.sub())
print(a.div())
>>>
6
8
2
2.0
객체가 생성될 때 자동으로 호출되는 메서드로 __init__이용
- 객체에 초깃값을 설정해야 할 필요가 있을 때에는 생성자를 구현하는 것이 안전한 방법
-> 객체가 생성되는 시점에 자동으로 호출
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
a = FourCal(4,2)
print(a.first)
print(a.second)
>>>
4
2
'Language > Python' 카테고리의 다른 글
정렬 itemgetter / attregetter (0) | 2020.12.11 |
---|---|
python swea 2005 파스칼의 삼각형 (0) | 2020.11.25 |
python swea 2056 연월일 달력 (0) | 2020.11.25 |
python swea 2068 최대수 구하기 (0) | 2020.11.25 |
python swea 2070 큰 놈, 작은 놈, 같은 놈 (0) | 2020.11.25 |