Skip to content

Latest commit

 

History

History
37 lines (29 loc) · 1.12 KB

File metadata and controls

37 lines (29 loc) · 1.12 KB

Instance Methods Exercises

Instance methods are functions that belong to objects and can access/modify the object's data through the self parameter.

Key Concepts

The self Parameter

  • First parameter of every instance method
  • Refers to the current object
  • Python automatically passes it when you call the method
class Example:
    def __init__(self, value):
        self.value = value
    
    def get_value(self):  # self is automatic
        return self.value

Types of Instance Methods

  • Getters: Return object data
  • Setters: Modify object data
  • Actions: Perform operations that may change state
  • Queries: Answer questions about the object

Method Design Principles

  • Methods should have a single, clear purpose
  • Use descriptive names that indicate what the method does
  • Consider whether the method should return a value or modify state
  • Keep methods focused and concise

Tips

  • Always include self as the first parameter
  • Use self.attribute to access instance variables
  • Methods can call other methods using self.method_name()
  • Consider returning self for method chaining