🎸

Objects and Classes in Python

Jul 15, 2024

Objects and Classes in Python

Creating a Class

  • Begin with defining a class, e.g., class Guitar:
  • Use the __init__ method to initialize class attributes. def __init__(self, self): self.n_strings = 6
  • Access these attributes by creating an object. my_guitar = Guitar() print(my_guitar.n_strings) # Outputs: 6

Methods in Classes

  • Methods add functionality to classes. def play(self): print('🎢')
  • Call methods on an object. my_guitar.play() # Outputs: 🎢
  • Automatically call a method within the __init__ method. def __init__(self, self): self.n_strings = 6 self.play()

Inheritance

  • Create a new class that inherits from an existing class. class ElectricGuitar(Guitar): pass
  • Add or override methods and attributes. class ElectricGuitar(Guitar): def play_louder(self): print('🎢'.upper())
  • Use the super() function to access parent methods. def __init__(self, self): super().__init__() self.n_strings = 8

Private Members

  • Use double underscores to make members private. self.__cost = 50 print(my_guitar.__cost) # Error
  • Access private members through class name. print(my_guitar._ElectricGuitar__cost) # Works ```__

Adding New Attributes

  • Modify __init__ method to accept new attributes. def __init__(self, self, n_strings=6): self.n_strings = n_strings
  • Create another class with minimal code repetition. class BassGuitar(Guitar): pass

Example Summary

  • Created classes and methods
  • Showed inheritance and adding/updating methods and attributes
  • Discussed private members and their limitations in Python
  • Demonstrated how to avoid code repetition using parameters with default values

Conclusion

  • Practice more with the