>>> class Cookie:
... pass
...
>>>
>>> a = Cookie()
>>> b = cookie()
객체와 인스턴스의 차이
a = Cookie() 이렇게 만든 a는 객체이다. 그리고 a 객체는 Cookie의 인스턴스이다.
관계 위주로 설명할 때 사용한다.
>>> class FourCal:
... pass
...
>>> a = FoulCal()
>>> type(a)
<class '__main__.FourCal'> //객체 a의 타입은 FourCal 클래스이다.
>>> class FourCal:
... def setdata(self, first, second):
... self.first = first
... self.second = second
...
>>> a = FourCal()
>>> a.setdata(4,2)
첫 번째 매개변수 self에는 setdata메서드를 호출한 객체 a가 자동으로 전달된다.
>>> class FourCal:
... def setdata(self, first, second):
... self.first = first
... self.second = second
... def add(self)
... result = self.first + self.second
... return result
객체에 초깃값을 설정해야 할 필요가 있을 때 사용
>>> class FourCal:
... def __init__(seslf, first, second):
... self.first = first
... self.second = second
기존 클래스를 변경하지 않고 기능을 추가하거나 기존 기능을 변경하려고 할 때 사용한다.
>>> class MoreFourCal(FourCal):
... def pow(self):
... result = self.first ** self.second //제곱 계산
... return result
>>>
부모 클래스에 있는 메서드를 동일한 이름으로 다시 만드는 것을 말한다.
>>> class SafeFourCal(FourCal)
... def add(self):
... if self.second == 0:
... return 0
... else:
... return self.first + self.second
...