目次
- 1 1. Introduction
- 2 2. What Are Python Methods? A Complete Explanation of How They Differ from Functions
- 3 3. Types of methods and how to use them (instance/class/static)
- 4 4. Learn Special Methods (Magic Methods)
- 5 5. Overview of Built-in Data Type Methods
- 6 6. Efficient Programming Examples Using Python Methods
- 6.1 6.1. Examples of Using Methods in Data Analysis
- 6.2 6.2. Examples of Using Methods for API Operations
- 6.3 6.3. Examples of Using Methods for File Operations
- 6.4 6.4. Examples of Applying Class Methods and Static Methods
- 6.5 6.5. Examples of Using Methods for Data Visualization
- 6.6 6.6. Key Points for Using Methods
- 7 7. Frequently Asked Questions (FAQ)
- 8 8. Summary and Next Steps
1. Introduction
Python is a popular programming language used by everyone from beginners to professionals. Among its concepts, methods are an essential part of learning Python programming. A method is a core element of object-oriented programming (OOP) and an important mechanism that supports Python’s flexibility and functionality. By understanding the difference between methods and functions—which often confuses beginners at first—and studying concrete examples, you can improve program efficiency and enable code reuse. This article provides a comprehensive explanation of Python methods, from basic concepts to practical examples. By reading this article, you will learn the following:- What methods are and how they differ from functions
- How to use instance methods, class methods, and static methods
- How to use Python’s special methods (magic methods)
- Useful methods provided by built-in data types like lists and dictionaries
- Practical examples of using methods

Ad
2. What Are Python Methods? A Complete Explanation of How They Differ from Functions
A Python method is something like a function used in the context of object-oriented programming (OOP). However, unlike a function, it has different characteristics, and the key point is that it operates bound to a specific object. In this section, we’ll explain the basics of methods and clearly distinguish them from functions.Definition and Characteristics of Methods
A method is a function defined inside a class. Methods are designed to operate on class instances and usually takeself as the argument that receives the instance. This self indicates which instance the method is bound to. Example: Basic structure of a methodclass SampleClass:
def example_method(self):
print("This is a method!")
# Create an instance and call the method
obj = SampleClass()
obj.example_method()Output:This is a method!In the example above, example_method is the method. It is called through the class instance obj, and self refers to that instance.Differences from functions
The differences between methods and functions can be summarized as follows.| Item | Method | Function |
|---|---|---|
| Definition location | Defined inside a class | Can be defined outside a class |
| How it’s called | Called through an instance or the class | Called directly |
| Binding | Associated with a specific object (self) | Not dependent on a specific object |
| Purpose | Manipulate an object’s data | Perform general-purpose operations |
def example_function():
print("This is a function!")
# Call the function directly
example_function()Purpose and benefits of methods
Methods offer significant advantages when manipulating an object’s data. For example, they make it efficient to initialize, update, and display data within a class. Using methods helps organize code and improve reusability. Example: Benefits of methodsclass Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def display(self):
print(f"Count: {self.count}")
counter = Counter()
counter.increment()
counter.increment()
counter.display()Output:Count: 2In this way, by using the increment and display methods of the Counter class, you can manipulate an instance’s state concisely and clearly.Choosing between functions and methods
- Functions:
- Use for general-purpose operations that don’t depend on a class.
- Example: functions for mathematical calculations or string manipulation (such as
len()orsum()). - Methods:
- Use when implementing behavior related to a class or object.
- Example: operations that change an object’s state or manipulate its data.

3. Types of methods and how to use them (instance/class/static)
Python has three types of methods. By understanding their roles and how to use them, you can effectively apply methods in the right situations. This section explains the differences between instance methods, class methods, and static methods, and how to use them.3.1. Instance methods
Overview Instance methods are methods that operate on a class instance (object). They receiveself as the first argument and can access or modify the instance’s attributes. Example: Using an instance methodclass Person:
def __init__(self, name):
self.name = name # Set an instance attribute
def greet(self):
print(f"Hello, my name is {self.name}.")
# Create an instance and call the method
person = Person("Alice")
person.greet()Output:Hello, my name is Alice.Main uses- Getting or modifying an instance’s attributes.
- Operations or processing related to a specific instance.
3.2. Class methods
Overview Class methods operate bound to the class itself. They receivecls as the first argument and can access or modify class-level data. When defining a class method, use the @classmethod decorator. Example: Using a class methodclass Circle:
pi = 3.14 # Class attribute
@classmethod
def calculate_area(cls, radius):
return cls.pi * radius ** 2
# Call directly from the class
area = Circle.calculate_area(5)
print(f"Area of the circle: {area}")Output:Area of the circle: 78.5Main uses- Manipulating data shared across the class.
- Defining alternative constructors for creating instances.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, data_string):
name, age = data_string.split(",")
return cls(name, int(age))
# Create an instance from string data
person = Person.from_string("Bob,30")
print(person.name, person.age)Output:Bob 303.3. Static methods
Overview Static methods perform independent operations that do not depend on an instance or the class. They do not receiveself or cls as the first argument. When defining a static method, use the @staticmethod decorator. Example: Using a static methodclass Math:
@staticmethod
def add(x, y):
return x + y
# Call directly from the class
result = Math.add(3, 5)
print(f"Sum: {result}")Output:Sum: 8Main uses- General-purpose processing that doesn’t depend on the class or instance state.
- Defining helper methods or utility functions.
3.4. Summary table of differences between methods
| Type | Decorator | First argument | Primary use |
|---|---|---|---|
| Instance methods | None | self | Operate on an instance’s attributes and data. |
| Class methods | @classmethod | cls | Manipulating class attributes and defining alternative constructors. |
| Static methods | @staticmethod | None | Perform general-purpose processing that does not depend on the class or instance. |

Ad
4. Learn Special Methods (Magic Methods)
Python’s special methods (magic methods) are used to customize specific behaviors and control how objects behave. They are characterized by having double underscores at both ends of their names (e.g.,__init__) and are also called “dunder methods”. This section covers commonly used special methods in Python programming, explained with examples.4.1. Basics of Special Methods
By overriding special methods in a class definition, you can customize behaviors such as the following:- Object initialization (e.g.,
__init__) - Defining string representations (e.g.,
__str__) - Customizing comparison operations (e.g.,
__eq__) - Changing operator behavior (e.g.,
__add__)
__init__ methodclass Product:
def __init__(self, name, price):
self.name = name
self.price = price
item = Product("Book", 1500)
print(item.name, item.price)Output:Book 15004.2. Commonly Used Special Methods
__init__: Object Initialization
- A method that is automatically called when creating an object.
- Used to initialize instance attributes of a class.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
item = Product("Book", 1500)
print(item.name, item.price)Output:Book 1500__str__: Object’s string representation
- Defines the string representation used when displaying with the
print()function or during string conversion.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name} costs {self.price} yen."
item = Product("Book", 1500)
print(item)Output:Book costs 1500 yen.__len__: Defining the object’s length
- Customizes how the built-in function
len()behaves.
class CustomList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_list = CustomList([1, 2, 3])
print(len(my_list))Output:3__eq__: Customize equality comparison
- Defines how the
==operator behaves.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
print(person1 == person2)Output:True__add__: Customize addition operation
- Defines how the
+operator behaves.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Point({self.x}, {self.y})"
point1 = Point(1, 2)
point2 = Point(3, 4)
result = point1 + point2
print(result)Output:Point(4, 6)4.3. Practical Examples of Special Methods
Example: Using special methods in a custom classclass BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def __str__(self):
return f"{self.owner}'s account balance: {self.balance} yen"
def __add__(self, other):
return BankAccount(self.owner, self.balance + other.balance)
account1 = BankAccount("Alice", 5000)
account2 = BankAccount("Alice", 3000)
merged_account = account1 + account2
print(merged_account)Output:Alice's account balance: 8000 yenIn this example, we use the special method __add__ to allow two bank accounts to be added together.4.4. Advantages of Special Methods
- Improved code readability: Operations on objects become more intuitive.
- Customizability: You can define behavior specific to your class.
- Leverage Python’s flexibility: You can extend built-in functions and operators.

5. Overview of Built-in Data Type Methods
Python provides built-in data types such as lists, dictionaries, and strings, and many convenient methods are available for them. This section focuses on commonly used methods for lists, dictionaries, and strings, explaining how to use each with examples.5.1. List (list) Methods
Lists are one of Python’s core data types and are very useful for handling collections of data.append()
Appends a new element to the end of the list. Examplefruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)Output:['apple', 'banana', 'cherry']extend()
Extends the list by appending elements from another list. Examplenumbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers)Output:[1, 2, 3, 4, 5, 6]insert()
Inserts an element at the specified position. Examplecolors = ["red", "blue"]
colors.insert(1, "green")
print(colors)Output:['red', 'green', 'blue']remove()
Removes the specified value from the list (only the first occurrence). Examplenumbers = [1, 2, 3, 2]
numbers.remove(2)
print(numbers)Output:[1, 3, 2]sort()
Sorts the elements of the list in ascending order. Examplenumbers = [5, 3, 8, 1]
numbers.sort()
print(numbers)Output:[1, 3, 5, 8]5.2. Dictionary (dict) Methods
Dictionaries are a data type well-suited for managing key-value pairs.get()
Retrieves the value for the specified key. If the key does not exist, returns a default value. Exampleperson = {"name": "Alice", "age": 30}
print(person.get("name"))
print(person.get("gender", "Not specified"))Output:Alice
Not specifiedkeys()
Gets all keys in the dictionary. Exampleperson = {"name": "Alice", "age": 30}
print(person.keys())Output:dict_keys(['name', 'age'])values()
Gets all values in the dictionary. Exampleperson = {"name": "Alice", "age": 30}
print(person.values())Output:dict_values(['Alice', 30])items()
Returns key-value pairs as tuples. Exampleperson = {"name": "Alice", "age": 30}
print(person.items())Output:dict_items([('name', 'Alice'), ('age', 30)])update()
Updates the dictionary. If a key exists, its value is overwritten; otherwise, a new key-value pair is added. Exampleperson = {"name": "Alice"}
person.update({"age": 30, "gender": "Female"})
print(person)Output:{'name': 'Alice', 'age': 30, 'gender': 'Female'}5.3. String (str) Methods
String manipulation is a common task in programming.upper()
Converts the string to all uppercase. Exampletext = "hello"
print(text.upper())Output:HELLOlower()
Converts the string to all lowercase. Exampletext = "HELLO"
print(text.lower())Output:helloreplace()
Replaces occurrences of a specified substring with another string. Exampletext = "I like Python"
print(text.replace("Python", "programming"))Output:I like programmingsplit()
Splits the string using the specified delimiter and returns a list. Exampletext = "apple,banana,cherry"
print(text.split(","))Output:['apple', 'banana', 'cherry']strip()
Removes leading and trailing whitespace from the string. Exampletext = " hello "
print(text.strip())Output:hello5.4. Using Built-in Data Type Methods
The methods introduced above are used very frequently in Python programming. By using them appropriately, you can write code that is concise and efficient.
Ad
6. Efficient Programming Examples Using Python Methods
By effectively leveraging Python methods, you can write complex operations succinctly and improve development efficiency. This section presents practical examples of using methods based on concrete scenarios.6.1. Examples of Using Methods in Data Analysis
In data analysis, lists and dictionaries are frequently manipulated. Using Python methods makes data shaping and manipulation easier. Example: Extracting data that meets specific conditions from a datasetdata = [
{"name": "Alice", "age": 25, "score": 85},
{"name": "Bob", "age": 30, "score": 90},
{"name": "Charlie", "age": 22, "score": 70}
]
# Extract people with scores of 80 or higher
filtered_data = [person for person in data if person["score"] >= 80]
print(filtered_data)Output:[{'name': 'Alice', 'age': 25, 'score': 85}, {'name': 'Bob', 'age': 30, 'score': 90}]Here, by combining dictionary access and list comprehensions, we concisely extract data that meets the conditions.6.2. Examples of Using Methods for API Operations
When using APIs, it’s often necessary to combine string manipulation with list processing. Example: Formatting data retrieved from an APIresponse = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True}
]
# Get the names of active users
active_users = [user["name"].upper() for user in response if user["active"]]
print(active_users)Output:['ALICE', 'CHARLIE']In this example, the upper() method is used to convert names to uppercase and extract only the data that meets the conditions.6.3. Examples of Using Methods for File Operations
Reading and writing files are basic operations in many programs. In Python, you can perform these operations succinctly by using built-in methods. Example: Reading and processing data from a text file# Create a file and write to it
with open("data.txt", "w") as file:
file.write("apple,banana,cherry
orange,grape,melon")
# Read the file and convert it to a list
with open("data.txt", "r") as file:
content = file.readlines()
# Process each line and store it in a list
data = [line.strip().split(",") for line in content]
print(data)Output:[['apple', 'banana', 'cherry'], ['orange', 'grape', 'melon']]In this example, the strip() and split() methods are used to format the file data.6.4. Examples of Applying Class Methods and Static Methods
By using class methods and static methods, you can modularize code and increase reusability. Example: User information processing classclass UserProcessor:
@staticmethod
def validate_email(email):
return "@" in email and "." in email
@classmethod
def from_csv(cls, csv_line):
name, email = csv_line.strip().split(",")
return {"name": name, "email": email, "valid": cls.validate_email(email)}
# Process CSV data
csv_data = [
"Alice,alice@example.com",
"Bob,bob_at_example.com",
"Charlie,charlie@example.com"
]
users = [UserProcessor.from_csv(line) for line in csv_data]
print(users)Output:[{'name': 'Alice', 'email': 'alice@example.com', 'valid': True},
{'name': 'Bob', 'email': 'bob_at_example.com', 'valid': False},
{'name': 'Charlie', 'email': 'charlie@example.com', 'valid': True}]In this example, a static method checks the validity of email addresses, and a class method generates user information from CSV data.6.5. Examples of Using Methods for Data Visualization
To visually represent data, it’s common to format lists and dictionaries and pass them to charting libraries. Example: Creating a bar chart from dictionary dataimport matplotlib.pyplot as plt
scores = {"Alice": 85, "Bob": 90, "Charlie": 70}
# Format the data
names = list(scores.keys())
values = list(scores.values())
# Plot the chart
plt.bar(names, values)
plt.title("Scores of Students")
plt.xlabel("Names")
plt.ylabel("Scores")
plt.show()In this example, the dictionary’s keys and values are converted into lists before plotting the chart.6.6. Key Points for Using Methods
- Choose the appropriate data type: Understand the characteristics of lists and dictionaries and use efficient methods.
- Actively use built-in methods: The methods provided by the standard library are optimized and efficient.
- Combine with list comprehensions: For conditional data operations, using list comprehensions keeps code concise.

Ad
7. Frequently Asked Questions (FAQ)
While learning Python methods, many people have questions. We’ve summarized them in an FAQ to help deepen your understanding of methods.Q1. How are methods different from functions?
Methods and functions are similar, but the main differences are as follows.| Item | Method | Function |
|---|---|---|
| Where defined | Inside a class | Can be defined outside a class |
| How they’re called | Called through an instance or the class | Called directly |
| Association | Associated with a particular object or class (uses self or cls) | Operate independently |
| Main purpose | Manipulate object data | Perform general-purpose tasks |
Q2. When do you use special (magic) methods?
Special methods (magic methods) are mainly used in the following situations.- Object initialization: Use
__init__to initialize attributes.
class Example:
def __init__(self, name):
self.name = name- Customize an object’s string representation: Use
__str__to control the output of print() and str().
class Example:
def __str__(self):
return "Custom String"- Customize operator behavior: Use
__add__and__mul__to modify how addition and comparisons behave.
class Number:
def __add__(self, other):
return "Custom Addition"Q3. What is the difference between class methods and static methods?
| Item | Class method | Static method |
|---|---|---|
| Decorator | @classmethod | @staticmethod |
| First argument | cls (receives the class itself) | None |
| What can be accessed | Can access class attributes and other class methods | General-purpose processing independent of the class or instance |
- Class method: Manipulate class-level data.
@classmethod
def method_name(cls):
pass- Static method: Perform independent calculations or transformations.
@staticmethod
def method_name():
passAd
8. Summary and Next Steps
8.1. Article Recap
We explored Python methods from basics to advanced topics. Methods are a crucial concept for understanding object-oriented programming and are essential for writing efficient, concise code. Below are the main points covered in this article.- Basics of Methods:
- A method is a function associated with a particular object; it can manipulate the object’s state or perform specific operations.
- Understanding how methods differ from functions lets you use them appropriately.
- Three Types of Methods:
- Instance methods: operate on instance attributes.
- Class methods: perform operations related to the class as a whole.
- Static methods: perform general-purpose operations that don’t depend on the class or instance.
- Special Methods (Magic Methods):
- They are used to customize object initialization, string representations, comparison operations, operator behavior, and more.
- Built-in Data Type Methods:
- Using the convenient methods built into lists, dictionaries, strings, and other types makes everyday data processing easier.
- Examples of Efficient Programming:
- We learned how to apply methods through practical scenarios such as data analysis, API interactions, and file handling.
- Answers to Common Questions:
- We cleared up questions about the differences between methods and functions, which methods beginners should learn, and how to use special methods.
8.2. Next Steps
With the basic knowledge of Python methods gained from this article, you’re ready to move on to the next steps. Below are recommended topics to study to further improve your skills.- Deepen Object-Oriented Programming (OOP):
- Using methods is part of OOP. Learn inheritance, polymorphism, abstract classes, and other concepts to understand the principles of object-oriented design.
- Study examples: class inheritance, design patterns.
- Decorators and Their Applications:
- Having learned class and static methods, you’ve grasped the basics of decorators. Next, move on to creating decorators and advanced usage.
- Study examples:
@property, creating custom decorators.
- Using the Standard Library and External Libraries:
- Python’s standard library includes many tools that enable efficient programming. Additionally, using external libraries allows for more advanced processing.
- Study examples: pandas, NumPy, matplotlib.
- Project-Based Learning:
- Working on real projects helps you learn practical uses of methods. Start with small projects and gradually increase the scope.
- Project examples: simple CRUD apps, data-processing scripts.
- Use Official Documentation:
- Make a habit of consulting Python’s official documentation to access the latest information. It also helps you learn unfamiliar methods and features.




