클래스
클래스는 프로그램의 틀이다.
클래스를 이용하여 틀을 만들고 그대로 객체를 찍어내면 된다.
그래서 클래스는 붕어빵 틀이고 객체는 붕어빵이라는 예시가 많다.
클래스 안에 있는 함수는 메서드라고 부른다.
class Greet():
def hello(self):
print("hello")
def hi(self):
print("hi")
human1=Greet()
human2=Greet()
human1.hello()
human1.hi()
human2.hello()
human2.hi()
hello
hi
hello
hi
클래스를 생성할 때 init 메서드를 사용하면 객체를 생성하지 않아도 메서드를 작성하는 것 만으로 바로 사용할 수 있다.
self는 자기 자신으로 클래스 메서드를 만들 때 사용한다.
class Student():
def __init__(self,name,age,like):
self.name=name
self.age=age
self.like=like
def student_info(self):
print(f"이름:{self.name},나이:{self.age},좋아하는것:{self.like}")
김철수=Student("김철수",17,"축구")
장다인=Student("장다인",5,"헬로카봇")
김철수.student_info()
장다인.student_info()
상속
class mother():
def characteristic(self):
print("키가 크다")
print("공부를 잘한다")
#daughter(mother) 클래스는 mother 클래스를 상속받는다.
class daughter(mother):
def characteristic(self):
super().characteristic()
print("운동을 잘한다")
#상속받은 메서드를 사용할 때는 super()를 사용한다.
엄마=mother()
딸=daughter()
print("엄마는")
엄마.characteristic()
print("딸은")
딸.characteristic()
엄마는
키가 크다
공부를 잘한다
딸은
키가 크다
공부를 잘한다
운동을 잘한다
init을 이용하여 객체를 생성하자마자 출력하는 방법이 있다.
class mother():
def __init__(self):
print("키가 크다")
print("공부를 잘한다")
class daughter(mother):
def __init__(self):
super().__init__()
print("운동을 잘한다")
'''
엄마=mother()
딸=daughter()
'''
#__init__의 사용으로 객체를 생성하지 않아도 바로 사용할 수 있다.
print("엄마는")
엄마.characteristic()
print("딸은")
딸.characteristic()
'파이썬' 카테고리의 다른 글
파이썬 append (0) | 2024.03.19 |
---|---|
파이썬 enumerate (0) | 2024.03.19 |
파이썬 개발환경 구성 (0) | 2024.03.19 |
파이썬 개발환경 세팅 연습 flask (1) | 2023.12.13 |
난생처음 파이썬 프로그래밍 리뷰~ 4장 데이터형과 문자열 (0) | 2023.10.18 |