Using an instance method inside another instance method in Python

So you’ve created a wonderful instance method for your class.

However, you would like to use the instance attributes created in that first instance method, in a second instance method WITHOUT calling the first instance method.

In that case you can use the following inside your second instance method: self.first_instance_method()

Python
# Using an instance method inside another instance method in Python
class VeryCoolClass:
  
    # Constructer method
    def __init__(self):
        pass

    # First instance method
    def first_instance_method(self):
        # Instance attribute
        self.instance_attribute = 'Look at this'

    # Second instance method that calls the first instance method
    def second_instance_method(self, add: str=' but not at this'):  # Default value of parameter "add" is ' but not at this'
        self.first_instance_method()

        # Printing the instance_attribute and adding the content of the "add" parameter
        print(self.instance_attribute + add)
    
# Instantiation (creating a new instance)
instance_of_very_cool_class = VeryCoolClass()

# Only calling the second instance; this means that the first_instance_method is called indirectly
instance_of_very_cool_class.second_instance_method(add=' but also at this!') # Output: Look at this but also at this!
Python

Leave Comment

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *