본문 바로가기

Python/Intermediate

[Python] Class(2) - self, 매직 매소드

# Chapter02-02
# 파이썬 심화
# 객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지 등
# 클래스 상세 설명
# 클래스 변수, 인스턴스 변수

# 클래스 재 선언
class Car():
    # Doctring """ ~ """
    """
    Car Class
    Author : Kim
    Date : 2019.11.08
    사용법:
    """

    # 클래스 변수, 모든 인스턴스가 공유함.
    car_count = 0

    # self 는 인스턴스 입니다.
    def __init__(self, company, details):
        self._company = company
        self._details = details
        Car.car_count += 1

    def __str__(self):
        return 'str : {} - {}'.format(self._company, self._details)

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

    def detail_info(self):
        print('Current Id : {}'.format(id(self)))
        print('Car Detail Info : {} {}'.format(
            self._company, self._details.get('price')))

    def __del__(self):
        Car.car_count -= 1

 

 

 


# Self 의미 - 인스턴스 자신을 의미.
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})

# ID 확인
print(id(car1))
print(id(car2))
print(id(car3))
# 140256586350544
# 140256586350352
# 140256586350016

print(car1._company == car2._company)
# 값을 비교한 것이므로 False
print(car1 is car2)
# 인스턴스를 비교한 것이므로 False, 메모리 값이 다름으로 알수 있음.

# dir, 이미 파이썬에서 만들어져 있는 매직메소드, 속성, 변수 등을 모두 보여줌. 리스트 형태로 출력됨.
# 내부 메소드, 내부 변수까지 보여줌. 모든 attr 을 다 보여줌.
print(dir(car1))
print(dir(car2))
# ['__class__', '__del__', '__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', 'car_count', 'detail_info']
# ['__class__', '__del__', '__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', 'car_count', 'detail_info']

print()
print()

# __dict__ 인스턴스 내부의 변수 및 값들만 보여줌. 딕셔너리 형태로 출력됨
print(car1.__dict__)
print(car2.__dict__)
# {'_company': 'Ferrari', '_details': {'color': 'White', 'horsepower': 400, 'price': 8000}}
# {'_company': 'Bmw', '_details': {'color': 'Black', 'horsepower': 270, 'price': 5000}}

인스턴스 매소드 접근 방법

 

# Doctring
print(Car.__doc__)
    # Car Class
    # Author : Kim
    # Date : 2019.11.08
    # 사용법:
print()

print('실행 - 인스턴스.메소드 or 클래스.메소드(인스턴스명)')
car1.detail_info()
car2.detail_info()
# Current Id : 140491737238640
# Car Detail Info : Ferrari 8000
# Current Id : 140491737238544
# Car Detail Info : Bmw 5000


print('에러 - 인스턴스명 전달없이 클래스.메소드() 는 오류')
# 에러
Car.detail_info() # self가 없어서 오류가 발생함.
---------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-1e5ad9f100b5> in <module>
     10 
     11 print('에러 - 인스턴스명 전달없이 클래스.메소드() 는 오류')
---> 12 Car.detail_info() # 에러 발생
     13 Car.detail_info(car1)
     14 Car.detail_info(car2)

TypeError: detail_info() missing 1 required positional argument: 'self'


Car.detail_info(car1)
Car.detail_info(car2)
# Current Id : 140479791893616
# Car Detail Info : Ferrari 8000
# Current Id : 140479791893520
# Car Detail Info : Bmw 5000

클래스 ID 접근방법 및 확인방법

 

# 비교
# 클래스 자체 아이디를 의미함. 그래서 모두 같음. 부모를 표시함
print('비교')
print(car1.__class__, car2.__class__)
print(id(car1.__class__), id(car2.__class__), id(car3.__class__))
print(id(car1.__class__) == id(car2.__class__) == id(car3.__class__))

# <class '__main__.Car'> <class '__main__.Car'>
# 140264212719104 140264212719104 140264212719104
# True

 

 


인스턴스 네임스페이스 없으면 상위에서 검색
즉, 동일한 이름으로 변수 생성 가능(인스턴스 검색 후 -> 상위(클래스 변수, 부모 클래스 변수))

 

# 클래스 변수
# 공유 확인
print()
print('클래스 변수, 공유 확인')
print(Car.__dict__)
print(car1.__dict__)  # 여기서는 클레스 변수인 car_count 변수가 보이지 않는다.
print(car2.__dict__)  # 여기서는 클레스 변수인 car_count 변수가 보이지 않는다.
print(car3.__dict__)  # 여기서는 클레스 변수인 car_count 변수가 보이지 않는다.
print(dir(car1))  # 여기서는 클레스 변수인 car_count 변수가 보임.
# {'__module__': '__main__', '__doc__': '\n    Car Class\n    Author : Kim\n    Date : 2019.11.08\n    사용법:\n    ', 'car_count': 3, '__init__': <function Car.__init__ at 0x7f9bc81328b0>, '__str__': <function Car.__str__ at 0x7f9bc8132940>, '__repr__': <function Car.__repr__ at 0x7f9bc81329d0>, 'detail_info': <function Car.detail_info at 0x7f9bc8132a60>, '__del__': <function Car.__del__ at 0x7f9bc8132af0>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>}
# {'_company': 'Ferrari', '_details': {'color': 'White', 'horsepower': 400, 'price': 8000}}
# {'_company': 'Bmw', '_details': {'color': 'Black', 'horsepower': 270, 'price': 5000}}
# {'_company': 'Audi', '_details': {'color': 'Silver', 'horsepower': 300, 'price': 6000}}
# ['__class__', '__del__', '__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', 'car_count', 'detail_info']


# 접근
print(car1.car_count)
print(car2.car_count)
print(Car.car_count)
# 3
# 3
# 3


del car2 # 인스턴스 삭제

print(car1.car_count)
print(Car.car_count)
# 2
# 2

# car2에 접근하면 에러 발생함.
# print(car2)
# NameError: name 'car2' is not defined

# 인스턴스 네임스페이스 없으면 상위에서 검색
# 즉, 동일한 이름으로 변수 생성 가능(인스턴스 검색 후 -> 상위(클래스 변수, 부모 클래스 변수))

'Python > Intermediate' 카테고리의 다른 글

[Python] NamedTuple - Magic Method(3)  (0) 2021.05.21
[Python] Magic Method(2)  (0) 2021.05.21
[Python] Magic Method(1)  (0) 2021.05.21
[Python] Class(3) - Class Method, Static Method  (0) 2021.05.21
[Python] Class(1) - Basic  (0) 2021.05.20