무회blog

Python # 파이썬 + - * / 연산을 할수 있는 클래스 (파이썬클래스) + 상속 본문

Python

Python # 파이썬 + - * / 연산을 할수 있는 클래스 (파이썬클래스) + 상속

최무회 2020. 5. 7. 16:21
# 파이썬 + - * /  연산을 할수 있는 클래스 
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(5,2) 
# a.setdata(8,2)
# print(a.first)        # a 객체에 first 변수가 추가됨 
# print(id(a.first))   # id 내장함수가 저장됨 

# b = FourCal() 
# b.setdata(7,3)
# print(b.first)
# print(id(b.first))

print(a.add())
print(a.mul())
print(a.sub())
print(a.div())

print(a.add() + a.mul())

 

상속 방식 

class MoreFourCal(FourCal):  #FourCal 클래스를 상속하는 MoreFourCal 클래스
    def pow(self):
        result = self.first ** self.second  
        return result

a = MoreFourCal(4, 2)

print(a.add())  #상속받은 FourCal 클래스의 기능을 모두 사용할 수 있음을 확인할 수 있다.
print(a.pow())  # a의 b제곱(ab)을 계산하는 MoreFourCal 클래스

Comments