Language/Python

생성자(Constructor)

olivia-com 2020. 12. 10. 06:43
class FourCal:
    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()
a.setdata(4,2)
print(a.add())
print(a.mul())
print(a.sub())
print(a.div())

>>>
6
8
2
2.0

객체가 생성될 때 자동으로 호출되는 메서드로 __init__이용

- 객체에 초깃값을 설정해야 할 필요가 있을 때에는 생성자를 구현하는 것이 안전한 방법

-> 객체가 생성되는 시점에 자동으로 호출

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(4,2)
print(a.first)
print(a.second)

>>>
4
2