본문 바로가기
프로그래밍/Python 관련 정보

[Python - Frequently Used Code] Class input argument

by 물박사의 저장공간 2024. 11. 22.

코딩하다가 자주 (제가...) 마주치는 오류를 정리해보려고 합니다. 

일단 제가 자주 범하는 실수는 ... 만일 함수나 클래스의 인풋 자체가 class일 경우인데요. class와 그 class의 instance는 분명 다른 개념입니다. 이런 경우에는 애초에 input argument로 instance를 받거나 그도 아니면 받아들이는 클래스 내부에서 instance화 해주어야 합니다.  

# 올바른 방식1 : instance를 전달
engine_instance = Engine(horsepower=150)
car = Car(engine_instance)

# 올바른 방식2 : 내부에서 instance화
class Car:
    def __init__(self, engine):
        if isinstance(engine, type):  # 엔진이 클래스인 경우 인스턴스화
            engine = engine(horsepower=100)  # 기본 horsepower로 초기화
        self.engine = engine
        print(f"Car has an engine with {self.engine.horsepower} horsepower.")

# 클래스 자체 전달해도 작동
car = Car(Engine)

 

만일 그냥 그대로 클래스를 넣어버리면..

class Engine:
    def __init__(self, horsepower):
        self.horsepower = horsepower

class Car:
    def __init__(self, engine):
        # engine은 Engine 클래스의 인스턴스라고 가정하고 사용
        self.engine = engine
        print(f"Car has an engine with {self.engine.horsepower} horsepower.")

# Engine 클래스 자체를 전달
car = Car(Engine)

 

AttributeError: type object 'Engine' has no attribute 'horsepower'

 

과 같은 에러를 마주치게 됩니다. 

 

이런 오류를 자주 접할 경우에 좀 더 방어적인 프로그래밍을 해주면 좋을 것 같아요. 아래처럼 isinstance를 통해서 미리 오류가 날 상황을 방지하고 있습니다. 

 

class Car:
    def __init__(self, engine: Engine):
        if not isinstance(engine, Engine):
            raise TypeError("engine must be an instance of Engine")
        self.engine = engine
        print(f"Car has an engine with {self.engine.horsepower} horsepower.")

# 올바른 방식: 인스턴스 전달
engine_instance = Engine(horsepower=200)
car = Car(engine_instance)