python-class-methods.md

#Python Class Methods

Methods are functions that belong to a class. They define the behavior of objects created from the class.

#Instance Methods

Create a method in a class:

pythonclass Person:
  def __init__(self, name):
    self.name = name

  def greet(self):
    print("Hello, my name is " + self.name)

p1 = Person("Emil")
p1.greet()
Note: All instance methods must have self as the first parameter, which refers to the specific instance of the object.

#Methods with Parameters

Methods can accept parameters just like regular functions:

pythonclass Calculator:
  def add(self, a, b):
    return a + b

  def multiply(self, a, b):
    return a * b

calc = Calculator()
print(calc.add(5, 3))
print(calc.multiply(4, 7))

#Methods Accessing Properties

Methods can access and modify object properties using self:

pythonclass Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def get_info(self):
    return f"{self.name} is {self.age} years old"

p1 = Person("Tobias", 28)
print(p1.get_info())

#Methods Modifying Properties

Methods can also update the internal state of an object:

pythonclass Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def celebrate_birthday(self):
    self.age += 1
    print(f"Happy birthday! You are now {self.age}")

p1 = Person("Linus", 25)
p1.celebrate_birthday()
p1.celebrate_birthday()

#The str() Method

The str() method is a special "dunder" (double underscore) method that controls what is returned when the object is represented as a string or printed.

Without the str() method: Printing the object returns the memory address.

pythonclass Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Emil", 36)
print(p1) # Output: <__main__.Person object at 0x...>

With the str() method:

pythonclass Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def __str__(self):
    return f"{self.name} ({self.age})"

p1 = Person("Tobias", 36)
print(p1) # Output: Tobias (36)

#Multiple Methods

A class can have multiple methods that work together to manage complex data:

pythonclass Playlist:
  def __init__(self, name):
    self.name = name
    self.songs = []

  def add_song(self, song):
    self.songs.append(song)
    print(f"Added: {song}")

  def remove_song(self, song):
    if song in self.songs:
      self.songs.remove(song)
      print(f"Removed: {song}")

  def show_songs(self):
    print(f"Playlist '{self.name}':")
    for song in self.songs:
      print(f"- {song}")

my_playlist = Playlist("Favorites")
my_playlist.add_song("Bohemian Rhapsody")
my_playlist.add_song("Stairway to Heaven")
my_playlist.show_songs()

#Delete Methods

You can delete methods from a class using the del keyword:

pythonclass Person:
  def __init__(self, name):
    self.name = name

  def greet(self):
    print("Hello!")

p1 = Person("Emil")

# Delete the method from the class definition
del Person.greet

p1.greet() # This will raise an AttributeError