배워서? 남줘라!
[Python] #8 Class 본문
class가 필요한 이유: 동일한 계산을 하는 함수가 여러개 필요할 때,
각각 만들지 않고 class 하나로 만들면 된다.
Class
#python8_Class
#1.더하기 계산기 만들기. (계산기는 이전 값을 기억하고 있다.)
class cal:
def __init__(self):
self.result = 0
def add(self, number):
self.result += number
return self.result
a= cal() #cal 더하기 계산기 역할을 하는 a라는 객체 생성.
b= cal() #cal 더하기 계산기 역할을 하는 b라는 객체 생성.
print(a.add(3))
print(a.add(4))
print(b.add(5))
print(b.add(2))
3
7
5
7
#2. class로 사칙연산 계산기 만들기.
class fourcal:
def setdata(self, first, second): #class 내부에 있는 함수(setdata)는 method라 함. method의 첫번째 매개변수는 보통 self 사용. 객체 자기자신 전달.
self.first=first
self.second=second
def add(self):
result =self.first + self.second
return result
def sub(self):
result = self.first - self.second
return result
def multi(self):
result = self.first * self.second
return result
def divi(self):
if self.second == 0:
return "can't calculate"
else:
result = self.first/self.second
return result
a1=fourcal()
b1=fourcal()
c1=fourcal()
a1.setdata(3,6)
b1.setdata(10,5)
c1.setdata(5,0)
print(a1.add())
print(b1.divi())
print(c1.divi())
9
2.0
can't calculate
#3. setdata 처럼 초기값을 설정해줄 필요가 있을 때에 class에는 생성자(constructor)를 구현.
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
a2 = fourcal(6,3) #a1.setdata(6,3) 안하고 바로 쓸 수 있다.
a2.add()
9
Class Inheritance (클래스 상속)
# Class inheritance (class의 기능 물려받음)
#Interitance1: fourcal1이라는 새로운 class생성하는데 fourcal이라는 class 기능 상속.
class fourcal1(fourcal):
pass
a3=fourcal1(6,3)
a3.add()
9
#Interitance2: fourcal2이라는 새로운 class생성하는데 fourcal 이라는 class 기능에 제곱 연산 메소드 추가.
class fourcal2(fourcal):
def pow(self):
result = self.first ** self.second
return result
a4=fourcal2(2,3)
a4.pow()
8
Method Overriding (덮어쓰기)
# Method overriding(덮어쓰기)
class fourcal2(fourcal):
def pow(self):
result = self.second ** self.first
return result
a5=fourcal2(2,3)
a5.pow()
9
Class 변수
# Class 변수 (위의 객체 변수를 더 자주 사용)
class Dog:
lastname = "A"
print(Dog.lastname)
aa=Dog()
print(aa.lastname)
Dog.lastname = "B"
print(aa.lastname)
print(id(Dog.lastname))
print(id(aa.lastname))
A
A
B
140576251340272
140576251340272
<참고>
박응용 저, Do it! 점프 투 파이썬, 이지스퍼블리싱, 2019
'Computer languages > Python' 카테고리의 다른 글
[Python] #9 Module & Package (0) | 2022.10.25 |
---|---|
[Python] #7 function (0) | 2022.10.14 |
[Python] #6 if, while, for (0) | 2022.10.09 |
[Python] #5 Bool & Variables (0) | 2022.10.07 |
[Python] #4 Dictionary & Set (1) | 2022.10.07 |
Comments