본문 바로가기
목차
Python

[Python] class 만들기.

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

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

Python에선 모든 것이 객체임: 아래의 class를 정의하면 CustomClass 라는 이름의 type 형의 객체가 생성됨:

class CustomClass (object):
	pass
  • class 키워드로 시작하는 클래스 정의하는 코드는 runtime에 실행되는 compound statement에 불과함.
  • CustomClasstype 을 형으로 가지는 object(객체)임.
  • 정확히는 type 은 Custom Class를 생성하는 metaclass 임.
ins = CustomClass()

# CustomClass 클래스의 instance: ins
print(f"{type(ins) = }") 

# type 클래스의 instance: CustomClass
print(f"{type(CustomClass) = }")
  • Python의 모든 클래스들은 type 형의 객체임.
  • 클래스들의 이름과 같은 이름을 가지는 함수가 바로 constructor(생성자)이며 해당 클래스의 instance를 반환함.

다음의 위의 코드의 실행 화면임:

 

여기에 동적으로 CustomClass 의 instance 인 ins에 attribute를 다음과 같이 추가할 수 있음:

ins.dynamic_attribute = 100 # dynamic_attribute 속성을 추가.

print(f"{ins.dynamic_attribute = }")

del ins.dynamic_attribute

print(f"{ins.dynamic_attribute = }")
  • Python의 모든 사용자가 만든 클래스는 type의 instance 이므로
  • Pythond의 instance (or 객체)가 동적으로 attribute를 추가할 수 있는 특성 을 사용자가 만든 클래스도 이 특성을 똑같이 가짐.
  • 때문에 다른 Python의 객체들 처럼 동적으로 attribute를 추가 및 삭제가 가능함.

다음의 객체 ins 에 동적으로 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 로 구성됨:

  • data attribute : 객체의 상태(state)를 나타내는 attribute
    • class attribute : Python에서 class object에 바인딩된 data attribute.
      • C++/Java의 static field와 비슷한 용도로 쓰일 수 있으나, 동일한 언어 구성요소는 아님.
    • instance attribute : instance variable 이라는 명칭도 많이 사용됨.
      • module 이나 package 등의 객체에 속하는 함수나 변수를 Python에선 모두 attribute라고 부름.
      • instance attribute는 해당 클래스를 type으로 하는 객체들의 state에 해당함.
  • method related attribute : 객체의 동작(behavior)을 나타내는 callable attribute
    • instance method : class namespace에 저장된 function object (instance 통해 접근 시 bound method로 변환됨.)
      • bound method는 이미 관련된 특정 instance가 첫 번째 인자 self로 묶인 method를 가리킴.
    •  class method : classmethod descriptor로 감싼 객체 (@classmethod 데코레이터).
      • 이 descriptor는 접근 시 호출한 class를 cls로 결합한 bound method를 반환
      • 여기서 bound method는 이미 해당 클래스가 첫 번째 인자 cls로 묶인 method를 가리킴.
    • static method : staticmethod descriptor로 감싼 객체(@staticmethod 데코레이터).
      • class나 instance를 통해 접근할 수 있으나,
      • instance method처럼 self가 자동 전달되지 않고 class method처럼 cls도 자동 전달되지 않음.
      • 따라서 class namespace 안에 논리적으로 묶어두고 싶은 일반 함수에 가까움.
instance에서 attribute를 찾을 때
instance namespace를 먼저 보고,
없으면 class namespace를 찾음

 

 

참고로,

C++/Java 에선

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

주의할 점은

  • Python은 Dynamic TypingRuntime Object Model을 사용하는 언어이기 때문에,
  • C++/Java의 static data member 와 동일한 별도의 언어 구성요소를 제공하지 않는다는 점이다.


Python에서 class-level data는 static data member가 아니라,
class object의 namespace에 저장된 일반 attribute이다.

따라서 Python의 class attribute는 여러 instance가 공유해서 참조할 수 있다는 용도 면에서는
C++/Java의 static field와 비슷하게 보일 수 있으나,
언어 모델상 C++/Java의 static data member와 완전히 동일시해서는 안 됨.

 

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/

 

BME

attribute bound-method class descriptor metaclass method object python type Python에서의 Class Class도 Python에서는 object임 다음은 Python에서 class와 object의 실체를 잘 보여준다. Python에서 대부분의 class는 object를 최상

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