Python Class

Happy_JG·2024년 4월 3일

Python

목록 보기
9/12
class Fruits(object):
    def __init__(self,name,tasty,ph):
        self.name = name
        self.tasty = tasty
        self.ph = ph

class WinterFruits(Fruits):
    def __init__(self,name,tasty,ph,birth_month):
        super().__init__(name,tasty,ph)
        self.birth_month = birth_month
    def __str__(self):
        return f"Name: {self.name}, Tasty: {self.tasty}, pH: {self.ph}, Birth Month: {self.birth_month}"

a = WinterFruits('strawberry','good','5.6','july')
print(a)

만약 상속 받고자 하는 속성이 따로 있다면

class Fruits(object):
    def __init__(self,name,tasty,ph):
        self.name = name
        self.tasty = tasty
        self.ph = ph

class WinterFruits(Fruits):
    def __init__(self,name,tasty,ph,birth_month):
        super().__init__(ph)
        self.birth_month = birth_month
    def __str__(self):
        return f"pH: {self.ph}, Birth Month: {self.birth_month}"

이렇게 super().__init__(ph) 만 컨트롤 하면 된다.

profile
hello!

0개의 댓글