classPerson: # 클래스 이름 defgreeting(self): # 메서드 print('Hi') # 코드
만든 클래스 사용해보기
1
ester = Person()
ester가 Person의 인스턴스(instance)이다.
클래스는 특정 개념을 표현만 할 뿐 사용하려면 인스턴스를 생성해야 한다.
객체를 생성해야 한다는 소리다.
메서드 호출하기
1
ester.greeting()
Hi
이렇게 인스턴스를 통해 호출하는 메서드를 인스턴스 메서드 라고 한다.
사칙연산 클래스 만들기
1 2
classFourcal: pass
1 2
a = Fourcal() type(a)
__main__.Fourcal
1 2 3 4
classFourcal: defsetdata(self, first, second): self.first = first self.second = second
1 2
a = Fourcal() a.setdata(4, 2)
setdata 메서드에는 총 3개의 매개변수(self, first, second)를 전달해줘야 할 것 같은데 왜 2개만 전달해줬을까?
self에는 객체 a가 자동으로 전달되기 떄문이다.
1 2 3 4
a = Fourcal() a.setdata(4, 2) print(a.first) print(a.second)
4
2
더하기 기능 만들기
1 2 3 4 5 6 7
classFourcal: defsetdata(self, first, second): self.first = first self.second = second defadd(self): result = self.first + self.second return result
1 2 3
a = Fourcal() a.setdata(4, 2) print(a.add())
6
빼기,곱하기, 나누기 추가
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classFourcal: defsetdata(self, first, second): self.first = first self.second = second defadd(self): result = self.first + self.second return result defmul(self): result = self.first * self.second return result defsub(self): result = self.first - self.second return result defdiv(self): result = self.first / self.second return result
1 2 3 4 5 6 7 8 9
a = Fourcal() b = Fourcal() a.setdata(4, 2) b.setdata(3, 8) print(a.add()) print(a.mul()) print(a.sub()) print(a.div())