History
home
BDA 연혁
home

- 클래스 사용하기 & 응용하기

클래스와 메서드 이해하기
클래스와 메서드 코드 이해하기
self란?
인스턴스와 self의 차이
self 코드 만들기
클래스를 이용한 간단한 게임 만들기!
게임 코드를 보며 클래스와 메서드 이해하기!
수업 예시 코드
# 예시 코드 class person: def __init__(self, name, age, address,wallet): self.hello = '안녕하세요!' self.name = name self.age = age self.address = address self.__wallet = wallet #변수 앞에 __ 비공개 속성 def greeting(self): print('{0} 저는 {1}입니다.'.format(self.hello, self.name)) def mutlpleage(self): print(self.age*self.age) def pay(self, amount): self.__wallet -=amount print('이제 {0}원 남았네요'.format(self.__wallet)) class Student: def __init__(self, name, age, grade='A', courses=None): self.name = name self.age = age self.grade = grade self.courses = courses or [] def enroll_course(self, course): """ 학생이 수강한 과목을 추가 Parameters: - course (str): 수강한 과목의 이름 """ self.courses.append(course) def display_student_info(self): """ 메서드: 학생 정보를 출력하는 메서드 """ print(f"Student Name: {self.name}") print(f"Age: {self.age}") print(f"Grade: {self.grade}") print("Courses Enrolled:") for course in self.courses: print(f" - {course}") print() student_instance = Student(name="John Doe", age=20, grade='B', courses=["Math", "Physics"]) student_instance.enroll_course("Chemistry") student_instance.display_student_info() ## keyword 인자 활용 class Product: def __init__(self, name, price, **kwargs): """ Parameters: - name (str): 제품의 이름 - price (float): 제품의 가격 - **kwargs: 기타 제품 속성을 키워드 인자로 받음 """ self.name = name self.price = price self.additional_attributes = kwargs def display_product_info(self): """ 제품 정보를 출력 """ print(f"Product Name: {self.name}") print(f"Price: ${self.price:.2f}") if self.additional_attributes: print("Additional Attributes:") for key, value in self.additional_attributes.items(): print(f" - {key}: {value}") print() product_instance = Product(name="Laptop", price=1200.0, brand="XYZ", memory="8GB", storage="256GB SSD") product_instance.display_product_info()
Python
복사