[IO] Class

DanA·2022년 9월 3일
1

python

목록 보기
1/4

객체 지향 프로그래밍(OOP)

코드의 재사용, 코드 중복 방지, 유지보수, 대형프로젝트를 위해.

클래스를 사용하여 자동차의 정보를 저장하는 클래스를 만들어봅시다.
구조 설계 후 재사용성 증가, 코드 반복 최소화, 메소드 활용 가능

class Car():
	""" # 3. __doc__
    Car class
    Author : Kim
    Date : 2022.09.03
    """
    def __init__(self, company, details):
        self._company = company
        self._details = details

	# 1. __str__메소드와 __repr__메소드
    def __str__(self): 
    	"""
        This is str docstring.
        """
        return 'str : {} - {}'.format(self._company, self._details)

    def __repr__(self):
        return 'repr : {} - {}'.format(self._company, self._details)

    def __reduce__(self):
        pass

# print(객체)을 하면 str 메소드가 있으면 str메소드가 출력되고, 아니면 repr 메소드가 출력됨

인스턴스를 만들어 보도록 한다.

car1 = Car('Ferrari', {'color' : 'White', 'horsepower': 400, 'price': 8000})
car2 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000})
car3 = Car('Audi', {'color' : 'Silver', 'horsepower': 300, 'price': 6000})

Class를 다루기 위해 반드시 알아야 할 메소드

__str__, __repr__, __dict__, __dir__, __doc__

1. __str__메소드와 __repr__메소드

어떤 class인지 알 수 있도록 __str__메소드나 __repr__메소드를 꼭 구현해놓는 것이 좋다.

  • __str__ : 비공식적인, print로 출력하는 사용자 입장의 출력을 할 때
    - __str__메소드는 다음과 같이 print문 없이 인스턴스를 그대로 출력하면 정보가 출력되지 않는 단점이 있다. 꼭 print문을 사용해주어야 한다.
  • __repr__ : 메소드객체를 그대로 표현해줄 때 & 엔지니어 레벨 객체의 엄격한 타입 정보 공식적인 문자열로 표현할 때 -> 이걸 더 많이 사용하는 것이 좋다.
    - __repr__은 인스턴스만 출력해도 정보가 나온다.

리스트로 선언(리스트 안에 객체로서 들어갈 땐 repr이 호출됨)

car_list = []

car_list.append(car1)
car_list.append(car2)
car_list.append(car3)

print(car_list)
[repr : Ferrari - {'color': 'White', 'horsepower': 400, 'price': 8000}, repr : Bmw - {'color': 'Black', 'horsepower': 270, 'price': 5000}, repr : Audi - {'color': 'Silver', 'horsepower': 300, 'price': 6000}]

리스트를 print문으로 출력 시에는 str정보가 나옴

for x in car_list:
    print(x)

for x in car_list:
    print(repr(x))
str : Ferrari - {'color': 'White', 'horsepower': 400, 'price': 8000}
str : Bmw - {'color': 'Black', 'horsepower': 270, 'price': 5000}
str : Audi - {'color': 'Silver', 'horsepower': 300, 'price': 6000}
repr : Ferrari - {'color': 'White', 'horsepower': 400, 'price': 8000}
repr : Bmw - {'color': 'Black', 'horsepower': 270, 'price': 5000}
repr : Audi - {'color': 'Silver', 'horsepower': 300, 'price': 6000}

2. __dict____dir__

  • __dict__ : 내부 속성을 볼 수 있음.
print(car1.__dict__)
{'_company': 'Ferrari', '_details': {'color': 'White', 'horsepower': 400, 'price': 8000}}
  • dir : 내부의 모든 메타 정보를 볼 수 있음.
print(car1.__dir__)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_company', '_details']

3. __doc__

docstring이란 클래스 docstring과 함수 docstring 두 가지가 있다. 우리는 위에서 두가지 모두 구현해놓았고 사용하는 방법은 다음과 같이 출력하면 된다.

  • 참고할 만한 reference : 1

Docstrings for Python Classes

print(Car.__doc__)

다음과 같이 나온다.

    Car class
    Author : Kim(성만 적기)
    Date : 2022.07.10

Docstrings for Python functions

print(Car.__str__.__doc__)
This is str docstring.

인스턴스 변수와 클래스 변수

profile
단아와라라

0개의 댓글