Method
Method
A function that belongs to an object. Defines the behavior of a class. Divided into instance methods, class methods, and static methods.
Method
A function that belongs to an object. Defines the behavior of a class. Divided into instance methods, class methods, and static methods.
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.
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) # 클래스 메서드 호출
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free