Understanding Instance Methods and Attributes in Python

Understanding Instance Methods and Attributes in Python

Introduction

In this tutorial, we will delve deeper into Python classes by exploring instance methods and attributes. We will expand on a basic class definition to include more attributes and methods, demonstrating how to create, access, and modify these elements.

Defining Instance Methods and Attributes

In the previous example, we created a simple Book class with a title attribute. Let’s enhance this class to include more information about a book, such as the author, number of pages, and price. We will also add methods to interact with these attributes.

Step 1: Expanding the __init__ Method

We start by expanding the __init__ method to include additional attributes.

				
					class Book:
    def __init__(self, title, author, pages, price):
        self.title = title
        self.author = author
        self.pages = pages
        self.price = price

				
			

The __init__ method initializes the title, author, pages, and price attributes of the Book instance.

Step 2: Adding Instance Methods

Next, we add methods to interact with the instance attributes. Instance methods operate on an instance of the class and can access and modify the instance’s attributes.

				
					class Book:
    def __init__(self, title, author, pages, price):
        self.title = title
        self.author = author
        self.pages = pages
        self.price = price
    
    def get_price(self):
        return self.price
    
    def set_discount(self, amount):
        self._discount = amount
    
    def get_discounted_price(self):
        if hasattr(self, '_discount'):
            return self.price - (self.price * self._discount)
        return self.price

				
			
  • get_price: Returns the price of the book.
  • set_discount: Sets a discount on the book.
  • get_discounted_price: Returns the price after applying the discount, if one is set.

Using the Class

Let’s create instances of the Book class and use the methods we defined.

				
					# Creating instances of the Book class
book1 = Book("War and Peace", "Leo Tolstoy", 1225, 39.95)
book2 = Book("Catcher in the Rye", "J.D. Salinger", 234, 29.95)

# Accessing attributes
print(book1.title)  # Output: War and Peace
print(book2.author)  # Output: J.D. Salinger

# Using instance methods
print(book1.get_price())  # Output: 39.95
book2.set_discount(0.25)
print(book2.get_discounted_price())  # Output: 22.46

				
			

Handling Private Attributes

In Python, private attributes can be indicated by prefixing the attribute name with an underscore. This is a convention to suggest that the attribute should not be accessed directly.

				
					class Book:
    def __init__(self, title, author, pages, price):
        self.title = title
        self.author = author
        self.pages = pages
        self.price = price
        self.__secret = "This is a secret attribute"

    def get_secret(self):
        return self.__secret

				
			

Attempting to access __secret directly from outside the class will result in an error:

				
					print(book1.__secret)  # AttributeError: 'Book' object has no attribute '__secret'

				
			

However, you can access it using the class name:

				
					print(book1._Book__secret)  # Output: This is a secret attribute

				
			

Conclusion

This tutorial demonstrates how to create and use instance methods and attributes in Python. By understanding these concepts, you can build more complex and functional classes, enhancing the power and flexibility of your code.