๐ Python
11. ํด๋์ค
sa1t
2022. 6. 9. 10:55
๋ฐ์ํ
# ํด๋์ค = ๊ฐ์ฒด ์งํฅ
# ํ, ์ค๊ณ๋, ํด๋์ค๋ฅผ ๋ง๋ค์ด ๋๊ณ
# ๋ณ์๋ช
๋ง ๋ฐ๊ฟ์ ๋น์ทํ ๋์์ ๋ค๋ฅธ ๊ฐ์ฒด๋ก ์คํ ์ํฌ ์ ์๋ค
result1 = 0
result2 = 0
def add1(num): # ๋งค๊ฐ๋ณ์ num
global result1
result1 = result1 + num
return result1
def add2(num): # ๋งค๊ฐ๋ณ์ num
global result2
result2 = result2 + num
return result2
print(add1(3))
print(add2(4))
##### ํด๋์ค ์ฌ์ฉํ ๋
class Calculator :
def __init__(self): # self๋ฅผ init(์ด๊ธฐํ) ์ํจ๋ค
self.result = 0 # ๋ณ์ ์ด๊ธฐํ ์ํค๊ธฐ ์ํ ์ฅ์น
def add(self,num): # ๋งค๊ฐ๋ณ์ num
self.result += num
return self.result
def sub(self,num):
self.result -= num
return self.result
cal1 = Calculator()
cal2 = Calculator()
print(cal1.add(3))
print(cal1.add(4))
print(cal1.sub(4))
print(cal2.add(4))
print(cal2.add(7))
print(cal2.sub(7))
##### ํ
์คํธ๋ฅผ ์ํ pass => ์๋ฌด๊ตฌ๋ฌธ์ ๋ฃ์ง ์์๋ ์๋ฌ๊ฐ ๋์ง ์์
class Cookie :
pass
a= Cookie()
b= Cookie()
### Quiz) ํด๋์ค๋ฅผ ์ฌ์ฉํ ์ฌ์น์ฐ์ฐ ๊ณ์ฐ๊ธฐ ๋ง๋ค๊ธฐ
# class Cal :
# input ๊ฐ ์
๋ ฅ ๋ฐ๊ธฐ
# if๋ฌธ ์ฌ์ฉ => +, -, * , / //add(),sub(),mul(),div() ๊ฐ์ฒด, ํจ์ ์ฌ์ฉ
while True:
class Cal:
def setdata(self,first,second,op):
self.first=first
self.op=op
self.second=second
first=int(input("์ฒซ๋ฒ์งธ ์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : "))
op=input("์ฐ์ฐ์(+, -, *, / )๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ")
second=int(input("๋๋ฒ์งธ ์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : "))
if op=="+":
def add(self):
result=self.first+self.second
return result
print("%d %s %d = %d " %(first,op,second,first+second))
elif op=="-":
def sub(self):
result = self.first - self.second
return result
print("%d %s %d = %d " %(first,op,second,first-second))
elif op=="*":
def mul(self):
result = self.first * self.second
return result
print("%d %s %d = %d " %(first,op,second,first*second))
elif op=="/":
def div(self):
result = self.first / self.second
return result
print("%d %s %d = %d " %(first,op,second,first/second))
else :
print("์๋ชป ์
๋ ฅ ํ์
จ์ต๋๋ค")
## ํด๋์ค ์์
# ํด๋์ค์์ ํด๋์ค๋ก ์์ฑ์ ๋ฌผ๋ ค ๋ฐ๋๊ฒ
## ์ฌ์น์ฐ์ฐ ๊ณ์ฐ๊ธฐ
class Cal:
def setdata(self,first,second):
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 mul(self):
result=self.first*self.second
return result
def div(self):
result=self.first/self.second
return result
a=Cal()
a.setdata(2,3)
print(a.add())
class Morecal(Cal):
def pow(self):
result=self.first ** self.second
return result
class Safecal(Cal):
def div(self):
if self.second ==0:
return 0
else:
result=self.first/self.second
return result
d=Safecal()
d.setdata(5,2)
print(d.div())
b=Morecal()
b.setdata(4,2)
print(b.add())
๋ฐ์ํ