Complete Guide to Python Methods: From Basics to Advanced

目次

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
This article is designed not only to help beginners understand the basics of Python methods but also to serve as a guide for intermediate and advanced users to learn more advanced usage. Now, first let’s take a closer look at “what a method is.”

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 take self as the argument that receives the instance. This self indicates which instance the method is bound to. Example: Basic structure of a method
class 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.
ItemMethodFunction
Definition locationDefined inside a classCan be defined outside a class
How it’s calledCalled through an instance or the classCalled directly
BindingAssociated with a specific object (self)Not dependent on a specific object
PurposeManipulate an object’s dataPerform general-purpose operations
Example: Basic structure of a function
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 methods
class 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: 2
In 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() or sum()).
  • 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 receive self as the first argument and can access or modify the instance’s attributes. Example: Using an instance method
class 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 receive cls 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 method
class 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.5
Main uses
  • Manipulating data shared across the class.
  • Defining alternative constructors for creating instances.
Example: Defining an alternative constructor
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 30

3.3. Static methods

Overview Static methods perform independent operations that do not depend on an instance or the class. They do not receive self or cls as the first argument. When defining a static method, use the @staticmethod decorator. Example: Using a static method
class 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: 8
Main 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

TypeDecoratorFirst argumentPrimary use
Instance methodsNoneselfOperate on an instance’s attributes and data.
Class methods@classmethodclsManipulating class attributes and defining alternative constructors.
Static methods@staticmethodNonePerform general-purpose processing that does not depend on the class or instance.

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__)
Example: Basics of the __init__ method
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

4.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.
Example
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.
Example
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.
Example
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.
Example
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.
Example
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 class
class 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 yen
In 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. Example
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
Output:
['apple', 'banana', 'cherry']

extend()

Extends the list by appending elements from another list. Example
numbers = [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. Example
colors = ["red", "blue"]
colors.insert(1, "green")
print(colors)
Output:
['red', 'green', 'blue']

remove()

Removes the specified value from the list (only the first occurrence). Example
numbers = [1, 2, 3, 2]
numbers.remove(2)
print(numbers)
Output:
[1, 3, 2]

sort()

Sorts the elements of the list in ascending order. Example
numbers = [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. Example
person = {"name": "Alice", "age": 30}
print(person.get("name"))
print(person.get("gender", "Not specified"))
Output:
Alice
Not specified

keys()

Gets all keys in the dictionary. Example
person = {"name": "Alice", "age": 30}
print(person.keys())
Output:
dict_keys(['name', 'age'])

values()

Gets all values in the dictionary. Example
person = {"name": "Alice", "age": 30}
print(person.values())
Output:
dict_values(['Alice', 30])

items()

Returns key-value pairs as tuples. Example
person = {"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. Example
person = {"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. Example
text = "hello"
print(text.upper())
Output:
HELLO

lower()

Converts the string to all lowercase. Example
text = "HELLO"
print(text.lower())
Output:
hello

replace()

Replaces occurrences of a specified substring with another string. Example
text = "I like Python"
print(text.replace("Python", "programming"))
Output:
I like programming

split()

Splits the string using the specified delimiter and returns a list. Example
text = "apple,banana,cherry"
print(text.split(","))
Output:
['apple', 'banana', 'cherry']

strip()

Removes leading and trailing whitespace from the string. Example
text = "   hello   "
print(text.strip())
Output:
hello

5.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.

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 dataset
data = [
    {"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 API
response = [
    {"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 class
class 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 data
import 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

  1. Choose the appropriate data type: Understand the characteristics of lists and dictionaries and use efficient methods.
  2. Actively use built-in methods: The methods provided by the standard library are optimized and efficient.
  3. Combine with list comprehensions: For conditional data operations, using list comprehensions keeps code concise.

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.
ItemMethodFunction
Where definedInside a classCan be defined outside a class
How they’re calledCalled through an instance or the classCalled directly
AssociationAssociated with a particular object or class (uses self or cls)Operate independently
Main purposeManipulate object dataPerform 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?

ItemClass methodStatic method
Decorator@classmethod@staticmethod
First argumentcls (receives the class itself)None
What can be accessedCan access class attributes and other class methodsGeneral-purpose processing independent of the class or instance
Use cases:
  • Class method: Manipulate class-level data.
@classmethod
def method_name(cls):
    pass
  • Static method: Perform independent calculations or transformations.
@staticmethod
def method_name():
    pass

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.
  1. 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.
  1. 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.
  1. Special Methods (Magic Methods):
  • They are used to customize object initialization, string representations, comparison operations, operator behavior, and more.
  1. Built-in Data Type Methods:
  • Using the convenient methods built into lists, dictionaries, strings, and other types makes everyday data processing easier.
  1. Examples of Efficient Programming:
  • We learned how to apply methods through practical scenarios such as data analysis, API interactions, and file handling.
  1. 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.
  1. 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.
  1. 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.
  1. 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.
  1. 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.
  1. 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.
Python documentation

The official Python documentation.…

8.3. Final Thoughts

By understanding and applying Python methods, you can improve code quality and solve problems more efficiently. From here, hone your skills through practical projects and further study so you can wield Python methods with confidence.