전공 공부/파이썬 기초

클래스

상솜공방 2023. 9. 13. 11:54

클래스 상속

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def get_name(self):
        print("My name is {}".format(self.name))
    def get_age(self):
        print("I'm {} years old".format(self.age))
        
class Student(Person): #부모 클래스를 상속 받으면 자동으로 변수와 기본 함수도 따라 온다.
    def __init__(self, name, age, GPA):
        super(Student, self).__init__(name, age) #부모 클래스의 메소드 호출
        #단순히 super().__init__(name, age)라고 적어도 되나
        #괄호 안에 자식 클래스와 self를 적어주면 현재 클래스가 어떤 것인지 명확히 표시 가능.
        self.GPA = GPA #Student 클래스에만 사용될 새로운 변수 추가

    def get_name(self): #메소드에 내용을 추가하고 싶다면?
        super().get_name(): #부모 클래스의 메소드 호출
        print("I'm studying in Inha university") #아래에 이어 적기

    def get_age(self): #부모 클래스의 메소드를 고쳐 쓰고 싶다면?
        print("I'm {} years old and I'm studying in computer science department".format(self.age))
		#그냥 이렇게 덮어쓰듯 적어주면 된다.
        
    def get_GPA(self): #Student 클래스에만 추가될 메소드 적기.
        print("My GPA is {}".format(self.GPA))

David = Person("David", 12)
David.get_name()
David.get_age()

Jane = Person("Jane", 18)
Jane.get_name()
Jane.get_age()

John = Student("John", 22, 4.3)
John.get_name()
John.get_age()
John.get_GPA()

결과:

My name is David
I'm 12 years old
My name is Jane
I'm 18 years old
My name is John
I'm 22 years old
My GPA is 4.3

 

클래스 메소드간 호출

class MultCalc:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        
    def mult(self):
        self.mult_result = self.a * self.b
        return self.mult_result
        
class SquareCalc(MultCalc):
    def __init__(self, a, b):
        super(SquareCalc, self).__init__(a, b)
    
    def square(self):
        self.temp = self.mult() # 상속받은 메소드를 부를 때는 self.***()로 호출.
        self.square_result = self.temp * self.temp
        return self.square_result
        
calc1 = MultCalc(2, 3)
calc1_mult = calc1.mult()
print(calc1_mult) # 6

calc2 = SquareCalc(2, 3)
calc2_square = calc2.square()
print(calc2_square) # 36