Python OOP Tutorial 4: Inheritance - Creating Subclasses

Python OOP Tutorial 4: Inheritance - Creating Subclasses

Understanding Python Class Inheritance

Introduction to Inheritance

  • The video introduces the concept of class inheritance in Python, explaining that it allows subclasses to inherit attributes and methods from a parent class.
  • Inheritance is useful for creating specific types of objects (subclasses) without duplicating code, enabling the addition or modification of functionality.

Creating Subclasses

  • The speaker uses an Employee class as a base example and proposes creating Developer and Manager subclasses, which share common attributes like name, email, and salary.
  • To create a subclass, one simply defines a new class with parentheses containing the parent class name. This establishes inheritance from the Employee class.

Functionality Inherited from Parent Class

  • By inheriting from the Employee class, the Developer subclass automatically gains all its attributes and methods without needing additional code.
  • Instances of both classes can be created seamlessly; when printing emails for developers created using inherited properties, they function correctly.

Method Resolution Order

  • When instantiating a developer object without its own initialization method (__init__), Python searches up the inheritance chain (method resolution order) to find it in the parent class.
  • The speaker demonstrates this process using Python's built-in help() function to visualize where Python looks for methods and attributes.

Customizing Subclass Behavior

  • The video discusses how to customize subclass behavior by changing specific attributes like raise amounts. For instance, developers can have different raise percentages than employees.

Understanding Subclassing in Python

Implementing a Developer Class

  • The employee class currently accepts first name, last name, and pay. To include programming language, the developer class will have its own __init__ method.
  • The __init__ method from the employee class is copied into the developer class, with an additional argument for programming language.
  • Emphasis on keeping code DRY (Don't Repeat Yourself); instead of copying code, use inheritance to maintain clean and maintainable code.
  • Using super().__init__() allows the developer class to inherit initialization logic for first name, last name, and pay from the employee class.
  • Preference for using super() over direct calls to parent methods; it enhances maintainability especially in multiple inheritance scenarios.

Setting Up Programming Language

  • After handling basic attributes through the employee's __init__, the developer can set their specific attribute: programming language.
  • When instantiating developers, programming languages like Python and Java are passed as arguments to ensure proper setup.
  • Verification of successful implementation by printing out attributes such as email and programming language after instantiation.

Creating a Manager Class

  • Introduction of another subclass called manager that inherits from employee; this subclass will manage a list of employees.
  • The manager's __init__ method allows passing a list of supervised employees with a default value set to None.
  • Explanation on avoiding mutable data types as default arguments; instead using None to initialize an empty list if no argument is provided.

Managing Employees

  • Implementation of methods within the manager class: adding and removing employees from their supervision list based on conditions.
  • Creation of an add_employee method that appends new employees only if they are not already in the list.

Displaying Supervised Employees

Manager Class Implementation

Overview of Manager Class Functionality

  • The manager class is designed to handle employee management, including attributes like first name, last name, pay, and a list of supervised employees.
  • A new manager instance is created with specific attributes: first name "Sue", last name "Smith", and a salary of 9,000. This instance supervises an initial developer.
  • The email address for the manager is printed to confirm correct attribute assignment and inherited methods from the employee class.

Employee Management Features

  • The method print_employees displays all employees under the manager's supervision. Initially shows one employee.
  • An additional employee can be added using add_employee, demonstrating dynamic list management within the class.
  • Employees can also be removed from the list; this showcases effective use of subclassing to manage unique functionalities for managers versus developers.

Understanding Inheritance in Python

Instance Checking Functions

  • Python provides built-in functions isinstance and issubclass to check object types and class hierarchies.
  • Using isinstance, it confirms that manager_one is indeed an instance of both Manager and Employee classes but not Developer.

Subclass Relationships

  • The function issubclass verifies if one class inherits from another. For example, both Developer and Manager are subclasses of Employee.
  • It clarifies that while both Manager and Developer inherit from Employee, they do not inherit from each other.

Real-world Application of Subclassing

Practical Example in Python Libraries

  • A practical example is found in the exceptions module within Python's Whiskey Library where HTTP exceptions inherit from a base exception class.
  • The HTTPException serves as a base for all HTTP-related errors, allowing derived classes like BadRequest to modify only necessary parts without rewriting common code.

Benefits of Inheritance

  • Utilizing inheritance simplifies code maintenance as projects grow larger by reusing existing code structures effectively.

Conclusion & Next Steps

Upcoming Topics

Video description

In this Python Object-Oriented Tutorial, we will be learning about inheritance and how to create subclasses. Inheritance allows us to inherit attributes and methods from a parent class. This is useful because we can create subclasses and get all of the functionality of our parents class, and have the ability to overwrite or add completely new functionality without affecting the parents class in any ways. Let's get started. Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM Python OOP 2 - Class Variables - https://youtu.be/BJ-VvGyQxho Python OOP 3 - Classmethods and Staticmethods - https://youtu.be/rq8cL2XMM5M Python OOP 4 - Inheritance - https://youtu.be/RSl87lqOXDE Python OOP 5 - Special (Magic/Dunder) Methods - https://youtu.be/3ohzBxoFHAY Python OOP 6 - Property Decorators - https://youtu.be/jCzT9XFZ5bw The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Object-Oriented ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python