Skip to content
Minsing Log
Go back

English Edition

What is a class method? How do you access methods of a nested class from a nested class?

Programming & CS

The reason for using a class method rather than an instance method when using methods in a nested class stems from the differences in the relationship between the nested and outer classes and the behavior of instance methods and class methods.


1. Relationship Between the Nested Class and the Outer Class

Because of this characteristic, an explicit connection between instances is required to use an instance of the outer class inside the nested class. In contrast, class methods are useful because they can be called without an instance of the outer class.


2. Difference Between Instance Methods and Class Methods

(1) Instance Methods

(2) Class Methods


3. Why Instance Methods Do Not Work in a Nested Class

Example: Problem When Using an Instance Method

class Outer:
    def __init__(self, name):
        self.name = name

    class Inner:
        def greet(self):  # 인스턴스 메서드
            return f"Hello from {self.name}"  # self.name에 접근 시 오류 발생

# 호출
outer = Outer("OuterInstance")
inner = outer.Inner()  # 이 코드는 오류 발생
inner.greet()

Result:

AttributeError: 'Inner' object has no attribute 'name'

4. Why Class Methods Solve the Problem

Solution Example: Using a Class Method

class Outer:
    name = "OuterClass"

    class Inner:
        @classmethod
        def greet(cls):
            return f"Hello from {cls.__name__}"

# 호출
outer = Outer()
inner = outer.Inner()  # 중첩 클래스 호출
print(inner.greet())

Result:

Hello from Inner

5. Summary of the Difference Between Instance Methods and Class Methods

CharacteristicInstance MethodClass Method
CallerInstance (self)Class (cls)
First parameterself (instance reference)cls (class reference)
Requires an instance of the outer classRequiredNot required
When availableAfter an instance is createdImmediately after the class is defined
Common usesManipulating instance attributes/methodsAccessing class attributes/methods, creating factory methods, etc.

6. When Should You Use a Class Method?

  1. Class-level operations:
    • When class attributes or class-level operations are needed.
  2. Independent operations without a connection to the outer class:
    • When no instance connection to the outer class is required, as with a nested class.
  3. Factory methods:
    • Use class methods to create objects according to specific conditions.

7. Summary

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Overfitting with k-fold cross-validation
Next Post
The Importance of Terms