Python class

https://wikidocs.net/28

1. 파이썬 클래스

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) <-- 생성자(Constructor) 생성과 동시에 4, 2가 __init__에 의해 입력 >>> print(a.first) 4 >>> print(a.second) 2

2. 클래스 상속

>>> class MoreFourCal(FourCal): ... def pow(self): ... result = self.first ** self.second ... return result

>>> a = MoreFourCal(4, 2) >>> a.pow() 16

3. 매서드 오버라이딩(Method Overriding)

>>> class SafeFourCal(FourCal): ... def div(self): ... if self.second == 0: # 나누는 값이 0인 경우 0을 리턴하도록 수정 ... return 0 ... else: ... return self.first / self.second

>>> a = SafeFourCal(4, 0) >>> a.div() 0

4. 클래스 변수

>>> class Family: ... lastname = "김" ...

>>> print(Family.lastname) 김






댓글