프로그래밍 언어/Python
[Python] 클래스와 상속
dev_tina
2022. 9. 22. 18:35
클래스
a = FourCal() # 자바 생성자를 쓰듯이(new 없음)
class FourCal:
def setDate(self, first, second): # self는 java의 this와 같은 개념
self.first = first
self.second = second
a = FourCal()
a.setDate(4,5)
숫자4 가 frist에, 5가 second에 들어가는 것
셋팅하고 갖다쓰고,
필요하면 새로 셋팅하고 갖다쓰는 개념
<계산기 예제>
class FourCal:
def setDate(self, first, second): # self는 java의 this와 같은 개념
self.first = first
self.second = second
def add(self): # 덧셈
result = self.first + self.second
return result
def minu(self): #뺄셈
result = self.first - self.second
return result
def mul(self): #곱셈
result = self.first * self.second
return result
def div(self): #나눗셈
result = self.first / self.second
return result
a = FourCal() # 자바 생성자를 쓰듯이(new 없음)
a.setDate(4,5)
a.add(), a.minu(), a.mul(), a.div()
여기서 name이 멤버변수처럼 보이지만 그렇지않다.
전역변수이다.
인스턴스
a.name 으로 가져올 수 있어야 멤버변수.
실제 멤버변수는 self. --- 값이다.
class FourCal:
name = 'hong' #전역변수 => 'class.__' 이와 같이 사용한다 / static
def __init__(self, first, second): # 파이썬은 오버라이딩 지원x , 동일한 이름을 줄 수 없음
self.first = first # this가 있는 멤버변수
self.second = second
def setDate(self, first, second): # self는 java의 this와 같은 개념
self.first = first
self.second = second
def add(self): # 덧셈
result = self.first + self.second
return result
def minu(self): #뺄셈
result = self.first - self.second
return result
def mul(self): #곱셈
result = self.first * self.second
return result
def div(self): #나눗셈
result = self.first / self.second
return result
두 점 사이의 거리를 구하는 클래스