프로그래밍/Python

[Python] 클래스

jaewoo93 2022. 11. 21. 21:23
class Student():
    def __init__(self,name,age,like):
        self.name = name
        self.age = age
        self.like = like
    def studentInfo(self):
        print(f"이름:{self.name}, 나이:{self.age}, 좋아하는 것:{self.like}")
   
김철수 = Student("김철수", 17, "축구")
장다인 = Student("장다인", 5, "헬로카봇")
김철수.studentInfo()
장다인.studentInfo()
 
 

__init__ 메서드는 객체를 만들 때 자동으로 동작하는 메서드

self는 자기 자신으로 클래스 메서드(함수)를 만들 때 꼭 붙여줘야 함.

----------------------------------------------------------------------------------------------------------------------------

 

<상속>

class Mother():
    def characteristic(self):
        print("키가 크다")
        print("공부를 잘한다")

class Daughter(Mother):
    def characteristic(self):
        super().characteristic()
        print("운동을 잘한다.")

엄마 = Mother()
= Daughter()
print("엄마는")
엄마.characteristic()
print("딸은")
.characteristic()

엄마는 키가 크다 공부를 잘한다

딸은 키가 크다 공부를 잘한다 운동을 잘한다.

 

 

super().characteristic() 로부터 상속받은 "키가 크다" "공부를 잘한다" 출력

상속받은 메서드(함수)를 사용할 때는 super()를 사용함.