클래스는 관련된 데이터(변수)와 기능(함수)을 하나로 묶은 설계도
ex. 자동차에서
# 학생 정보를 관리하는 프로그램
student1_name = "김철수"
student1_age = 20
student1_grade = "A"
student2_name = "이영희"
student2_age = 22
student2_grade = "B"
# 학생 정보 출력 함수
def print_student_info(name, age, grade):
print(f"이름: {name}, 나이: {age}, 성적: {grade}")
# 학생 정보 업데이트 함수
def update_grade(current_grade):
if current_grade == "B":
return "A"
return current_grade
# 학생 정보 출력
print_student_info(student1_name, student1_age, student1_grade)
print_student_info(student2_name, student2_age, student2_grade)
# 영희의 성적 업데이트
student2_grade = update_grade(student2_grade)
print(f"{student2_name}의 성적이 {student2_grade}로 업데이트되었습니다.")
# 학생 클래스 정의
class Student:
def __init__(self, name, age, grade): # 생성자 함수
self.name = name
self.age = age
self.grade = grade
def print_info(self):
print(f"이름: {self.name}, 나이: {self.age}, 성적: {self.grade}")
def update_grade(self):
if self.grade == "B":
self.grade = "A"
return self.grade
# 학생 인스턴스 생성
student1 = Student("김철수", 20, "A")
student2 = Student("이영희", 22, "B")
# 학생 정보 출력
student1.print_info()
student2.print_info()
# 영희의 성적 업데이트
student2.update_grade()
print(f"{student2.name}의 성적이 {student2.grade}로 업데이트되었습니다.")
class 클래스명:
# 클래스 내용
def __init__(self, 매개변수들):
self.속성명 = 값
def 메서드명(self, 매개변수들):
# 기능 구현
return 결과
객체명 = 클래스명(인자들)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "0으로 나눌 수 없습니다."
# 연산 수행
num1 = 10
num2 = 5
print("덧셈:", add(num1, num2))
print("뺄셈:", subtract(num1, num2))
print("곱셈:", multiply(num1, num2))
print("나눗셈:", divide(num1, num2))
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def subtract(self):
return self.a - self.b
def multiply(self):
return self.a * self.b
def divide(self):
if self.b != 0:
return self.a / self.b
else:
return "0으로 나눌 수 없습니다."
def power(self):
return self.a ** self.b
# 계산기 인스턴스 생성
calc1 = Calculator(10, 5)
# 각종 연산 수행
print("덧셈:", calc1.add()) # 15
print("뺄셈:", calc1.subtract()) # 5
print("곱셈:", calc1.multiply()) # 50
print("나눗셈:", calc1.divide()) # 2.0
print("거듭제곱:", calc1.power()) # 100000 (10의 5승)
# 다른 숫자로 새로운 계산기 생성
calc2 = Calculator(20, 4)
print("새로운 계산기 덧셈:", calc2.add()) # 24
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
return f"안녕하세요, {self.name}님!"
def say_age(self):
return f"{self.name}님의 나이는 {self.age}살입니다."
def get_info(self):
return f"이름: {self.name}, 나이: {self.age}"
person = Person("김철수", 25)
print(person.say_hello())
print(person.say_age())
print(person.get_info())
# 안녕하세요, 김철수님!
# 김철수님의 나이는 25살입니다.
# 이름: 김철수, 나이: 25