매직 키워드

임승환·2024년 4월 4일

Python

목록 보기
11/20
  • init
def ws_7_1():
    class Shape:
        def __init__(self, a, b):
            # 인스턴스 메서드 (속성)값을 접근하려면
            # self 키워드를 통해서 접근을 해야한다.
            # 인스턴스 변수
            self.width = a
            self.height = b

    shape1 = Shape(5, 3)
    print(shape1.width, shape1.height)

ws_7_1()
# 5, 3
def ws_7_2():
    # ws_7_2.py

    # 아래 클래스를 수정하시오.
    class Shape:
        def __init__(self, width, height):
            self.width = width
            self.height = height

        def calculate_area(self):
            return self.width * self.height

    shape1 = Shape(5, 3)
    area1 = shape1.calculate_area()
    print(area1)

ws_7_2()
# 15 인스턴스 메서드를 만들어서 출력
  • @staticmethod
def hw_y_2():
    class StringRepeater:

        @staticmethod
        def repeat_string(r, hi):
            for _ in range(r):
                print(hi)

    repeater1 = StringRepeater()
    repeater1.repeat_string(3, "Hello")

hw_y_2()
  • 생성자 생성될 때마다 카운트
def hw_y_4():
    class Person:
        number_of_people = 0

        def __init__(self, name, old):
            self.name = name
            self.old = old
            Person.number_of_people += 1

        def introduce(self):
            print(f'제 이름은 {self.name} 이고, 저는 {self.old} 살 입니다.')

    person1 = Person("Alice", 25)
    person1.introduce()
    print(Person.number_of_people)

hw_y_4()
  • str
  • 해당 객체의 속성을 문자열로 반환
def ws_7_5():
    class Shape:
        def __init__(self, width, height):
            self.width = width
            self.height = height

        def __str__(self):
            return f'Shape: width={self.width}, height={self.height}'

    shape1 = Shape(5, 3)
    print(shape1)

ws_7_5()
profile
주니어 개발자

0개의 댓글