본문 바로가기
목차
Python

[Python] class 만들기.

by ds31x 2024. 4. 14.
728x90
반응형

Python에서의 custom class 만들 때 미리 알고있어야 하는 내용.

  • Python에선 모든 것이 객체임: 아래의 class를 정의하면 CustomClass 라는 이름의 type 형의 객체가 생성됨:
    • class 키워드로 시작하는 클래스 정의하는 코드는 runtime에 실행되는 compound statement에 불과함.
    • CustomClasstype 을 형으로 가지는 object(객체)임.
    • 정확히는 type은 Custom Class를 생성하는 metaclass 임.
  • Python의 모든 클래스들은 type 형의 객체임.
  • 때문에 다른 Python의 객체들 처럼 동적으로 attribute를 추가 및 삭제가 가능함.

보다 자세한 내용은 다음을 읽어볼 것:

2025.12.24 - [Python] - Python Class Definition and Object Model

 

Python Class Definition and Object Model

1. Object-Oriented Programming (OOP)에서의 Class 개념1.1 Class의 역할Class = State + Behavior Class는 Object-Oriented Programming에서 State와 Behavior를 함께 정의하는 추상화 단위임State는 Object가 보유하는 데이터의 집합

ds31x.tistory.com


Class가 가지는 attributes의 종류:

class는 state와 behavior를 묶는 개념이며, 이들에 대해 다음의 attributes를 가지는게 일반적임.

  • class (data) attribute : C++과 Java에선 class attribute는 static attribute임.
  • instance (data) attribute
  • class method (attribute)
  • static method (attribute)
  • instance method (atribute)

참고로, C++/Java 에선

  • data attribute보다는 member variable이나 field라는 용어가 더 많이 애용되며,
  • method 외에 member function이라는 용어도 자주 사용됨.

주의할 점은 Python은 Dynamic TypingRuntime Object Model을 사용하는 언어이기 때문에,
기존 언어에서의 static data member 개념이 존재하지 않으며,
class-level data는 단순히 class object의 attribute로 표현된다.
따라서 Python의 class data attribute를 static attribute로 동일시하면 안 된다.

Python에서 class data attribute는
static data member가 아니라,
class object가 런타임에 가지는 일반적인 속성(attribute)이다.

 

 

참고: 2025.12.09 - [Python] - Typing: dynamic vs. static and strong vs. weak

 

Typing: dynamic vs. static and strong vs. weak

타입 검사는 프로그램의 type safety를 보장하기 위한 장치이며, 언제(컴파일/실행 시점) 검사하느냐와 얼마나 엄격하게 검사하느냐에 따라 프로그래밍 언어가 분류됨:Static vs Dynamic: 언제 타입을

ds31x.tistory.com


Python에서 Class 는 동적으로 속성 및 구조 변경이 가능함:

 

이는 custom type(=user-defined type)을 정의하고 있는 class 자체가 run-time에 생성되는 object이기 때문임.

 

때문에, 다음을 명심해야 한다:

  • 일반적으로 C++/Java 등에서 class 가 정의되고 나면 해당 class의 attributes 나 구조를 변경하지 못하는 것과 달리,
  • Python은 동적으로 attribute 추가 등의 구조 변경이 가능함.

이같은 특성을 가지나, 동적으로 속성을 추가하는 건 매우 심각한 문제점을 만들기 쉬운 구조이다 보니

Python에선 instance data attribute를 가급적 __init__(...) 메서드에서 self의 attribute로 설정하는 방식을 권장하고 있음
(강제하고 있진 않지만, 반드시 이 방식을 사용할 것을 강력하게 권함)


권장되는 일반적인 class 만드는 법

일반적으로 class 만드는 법은 다음 코드를 참고할 것.

class CustomClass (SuperClass0, SuperClass1) : # class 정의 헤더. 클래스의 이름과 부모를 지정.

    # class attributes
    class_variable0 = None # class가 가지는 attribute를 assignment로 생성.

    @classmethod # @classmethod 데코레이터를 통해 class method를 정의
    def class_method(cls, *args): # class method 정의 (필요하지 않은 경우가 많음)
        # 첫번째 파라메터 cls에 class method를 호출하는 class객체가 할당됨.
        print(f'{cls.class_variable0=}')


    # instance attributes
    def __init__(self, *args):
        # 생성자. 반드시 만들고, 여기서 instance attribute를 할당으로 추가함.
        # self 는 생성되는 instance를 가르킴.
        super().__init__()             # 부모 클래스의 생성자는 거의 대부분 꼭 호출해줘야함. 
        self.instance_variable0 = None # instance attribute를 assignment로 생성.
        self.instance_variable1 = None # instance attribute를 assignment로 생성.

    def instance_method(self, *args): # instance method 정의.
        print(type(self).class_variable0)  # class variable에 접근 가능.
        print(CustomClass.class_variable0) # class이름으로 class variable에 접근.
        print(self.instance_variable0)     # instance variable에 접근 가능.


    # static attributes
    @staticmethod # @staticmethod 데코레이터를 통해 static method를 정의
    def static_method(): # static method 정의  (필요하지 않은 경우가 많음)
        # instance의 variable을 바꾸지 않는 pure function 만드는데 사용됨.
        # class method로 거의 대부분 대처 가능하므로 많이 사용되지 않음.
        print(CustomClass.class_variable0)          # class이름으로 class variable에 접근.
  • 모든 instance들이 공유해야하는 변수가 존재한다면, class attribute로 만들 것.
  • 해당 class attribute에만 접근하는 어떤 처리가 필요하고, 
    굳이 instance의 상태에 상관없을 경우 class methods로 만들 것.
  • class attributes나 instance attributes 모두 동적으로 추가가능하지만, 
    위의 예제처럼 추가하는 것을 권함 (동적 속성 추가는 피하는게 좋음).
  • 특히, instance (data) attributes는 모두 __init__(...) 메서드에서 초기화 하는 것을 강력하게 권함.

참고자료

동적 속성 추가관련 자료.

https://dsaint31.me/mkdocs_site/python/oop/oop_3_01_python_class/#class-attribute

 

BME228

Python에서의 Class Class 도 Python에서는 instance임. 다음이 Python에서 Class와 Object의 실체를 말해준다. 모든 Object는 Object를 super-class로 가진다. 모든 Class는 type이라는 Class의 instance이다. 우리가 Samp1 이

dsaint31.me

 

instance methods, class methods and static methods 에 대한 자료.

2023.08.20 - [Python] - [Python] instance methods, class methods, and static methods

 

[Python] instance methods, class methods, and static methods

method 의 경우,instance method,class method,static method 로 나뉘지만,field(=variable attribute)의 경우엔, instance variable (=instance data attribute)과 class variable(=class data attribute)만 있음.2025.12.24 - [Python] - Python Class Defi

ds31x.tistory.com

 

decorator에 대한 자료

2023.08.18 - [Python] - [Python] Decorator

 

[Python] Decorator

Python이 제공하는 Decorator는 기존의 function을 수정하지 않으면서 특정 처리를 추가할 수 있게 해주는 도구.Decorate의 "꾸미다"라는 의미에 맞게 기존 function을 꾸며주는 기능을 제공한다.Decorator를

ds31x.tistory.com


 

728x90