💻 Programming

Method

Method

A function that belongs to an object. Defines the behavior of a class. Divided into instance methods, class methods, and static methods.

📖 Detailed Explanation

A method is a function that belongs to an object and defines the actions a class can perform. Unlike a regular function, a method can access and modify the object's state (fields) and runs in the context of the object.

Methods fall into three broad types. Instance methods are called on an object instance and access instance data through this/self. Class methods are called on the class itself and access class attributes through cls. Static methods operate independently of any instance or class.

Method overloading (same name, different parameters) and overriding (inheriting and redefining) are key techniques for implementing polymorphism. Java and C++ support overloading, but Python does not support it by default, so default values or *args are used to achieve a similar effect.

Getter/setter methods control access to fields. Python's @property decorator and Java's accessor/mutator pattern are representative examples. This makes it possible to add value validation or additional logic while maintaining encapsulation.

💻 Code Example

Python
class BankAccount:
    interest_rate = 0.02  # 클래스 변수

    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance  # 보호된 속성

    # 인스턴스 메서드: self를 통해 인스턴스 접근
    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            return True
        return False

    def withdraw(self, amount):
        if 0 < amount <= self._balance:
            self._balance -= amount
            return True
        return False

    # Property: getter/setter 역할
    @property
    def balance(self):
        return self._balance

    # 클래스 메서드: cls를 통해 클래스 접근
    @classmethod
    def set_interest_rate(cls, rate):
        cls.interest_rate = rate

    # 정적 메서드: 인스턴스/클래스와 무관
    @staticmethod
    def validate_amount(amount):
        return isinstance(amount, (int, float)) and amount > 0

# 사용 예시
account = BankAccount("김개발", 1000)
account.deposit(500)
print(f"잔액: {account.balance}")  # 1500
BankAccount.set_interest_rate(0.03)  # 클래스 메서드 호출

🗣️ Examples of Practical Conversations

Junior Developer
"I don't know where to put this utility function. Should I put it inside a class?"
Senior developer
"If it doesn't use instance state, it's better to make it a static method or a module-level function. There's no need to bind it to a class unnecessarily."
Junior Developer
"What's the difference between a static method and a class method?"
Interviewer
"Please explain the difference between method overloading and overriding."
Candidate
"Overloading is defining methods with the same name but different parameters, and overriding is redefining a superclass method in a subclass."
Interviewer
"How do you create a private method in Python?"
Candidate
"Starting a name with two underscores applies name mangling, like __method. But it isn't truly private; by convention, it just indicates that the method is for internal use."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"This method is over 20 lines long. A single method should do only one thing. Please split it up."
Author
"I'll split the validation, transformation, and storage steps into separate private methods."
Reviewer
"And please mark methods that don't use self with @staticmethod. It makes the intent clear."

⚠️ Cautions

🔗 Related Terms

📚 Learn More