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

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


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