프로그래밍/Python

파이썬 - 클래스 개념

Terry Cho 2025. 3. 19. 16:48

파이썬 클래스 개념

  • 다른 언어와 마찬가지로 인스턴스 변수와 메소드가 있고, 클래스 변수와 메소드가 있다. 
class Circle:
    # 클래스 변수: 원주율
    pi = 3.14159

    def __init__(self, radius):
        # 인스턴스 변수: 반지름
        self.radius = radius

    # 인스턴스 메서드: 원의 넓이 계산
    def area(self):
        return Circle.pi * (self.radius ** 2)

    # 인스턴스 메서드: 원의 둘레 계산
    def circumference(self):
        return 2 * Circle.pi * self.radius

    # 클래스 메서드: 원주율 변경
    @classmethod
    def set_pi(cls, new_pi):
        cls.pi = new_pi


# 원 객체(인스턴스) 생성
circle1 = Circle(5)  # 반지름이 5인 원

# 원의 넓이와 둘레 계산 (인스턴스 메서드 호출)
print(f"Circle 1 - Area: {circle1.area()}, Circumference: {circle1.circumference()}")

# 원주율 변경 (클래스 메서드 호출)
Circle.set_pi(3.14)
print(f"Circle 1 - Area: {circle1.area()}, Circumference: {circle1.circumference()}")

 

클래스간 상속 및 메서드 오버라이드

  • 상속은 클래스 정의시 class 클래스명(상속할 부모 클래스명) 식으로 정의한다.
  • 예시 class Cat(Animal)
class Animal:  # 부모 클래스
    def speak(self):
        print("동물이 소리를 냅니다.")

class Dog(Animal):  # Animal을 상속받는 자식 클래스
    def speak(self):  # 메서드 오버라이딩
        print("멍멍!")

class Cat(Animal):  # Animal을 상속받는 또 다른 자식 클래스
    def speak(self):  # 메서드 오버라이딩
        print("야옹!")

# 객체 생성
animal = Animal()
dog = Dog()
cat = Cat()

# 메서드 호출
animal.speak()  # 출력: 동물이 소리를 냅니다.
dog.speak()     # 출력: 멍멍!
cat.speak()     # 출력: 야옹!

 

'프로그래밍 > Python' 카테고리의 다른 글

파이썬 - yield 키워드  (0) 2025.03.19
파이썬 - pass 키워드  (0) 2025.03.19
Python yield  (0) 2024.08.06
파이썬 전역 변수  (0) 2017.04.11
django 에서 REST API 만들기  (2) 2014.01.08