Python OOP Tutorial 2: Class Variables

Python OOP Tutorial 2: Class Variables

Understanding Class Variables in Python

Introduction to Instance and Class Variables

  • The video begins with a recap of creating a simple class and instances, focusing on instance variables that hold unique data for each instance.
  • A brief mention of class variables is made, which are shared among all instances of a class, contrasting them with instance variables.

Use Case for Class Variables

  • The speaker introduces the concept of annual raises as an example where class variables would be beneficial since the raise amount is consistent across all employees.
  • Before implementing the class variable, the speaker hard codes the raise amount into a method called apply_raise to illustrate why using a class variable is advantageous.

Implementing Class Variables

  • The apply_raise method modifies an employee's pay by applying a 4% increase. This demonstrates how raises can be applied but highlights limitations in accessing the raise amount.
  • The need for easy access to the raise amount through both instances and classes is emphasized; currently, it’s hard-coded within methods.

Transitioning to Class Variable Implementation

  • To improve code maintainability, the speaker suggests moving the hard-coded 4% into a class variable defined at the top of the employee class.
  • Accessing this new raise_amount variable requires referencing it through either the employee class or its instances.

Understanding Access to Class Variables

  • An explanation follows about how accessing attributes works: if an instance does not have an attribute, Python checks if it's available in its parent class.
  • Demonstrations show that both instances and classes can access raise_amount, clarifying how inheritance affects attribute visibility.

Exploring Namespace and Attribute Visibility

  • The speaker prints out various attributes from an instance to illustrate that while individual instances do not contain raise_amount, they can still access it via their parent class.
  • By examining namespaces further, it becomes clear that changes made to raise_amount affect all instances due to its shared nature as a class variable.

Conclusion on Modifying Class Variables

Understanding Instance and Class Variables in Python

Instance Variables vs. Class Variables

  • The discussion begins with the concept of using instance variables, where employee1.raise_amount is set to 5%, affecting only that specific instance.
  • When checking employee1's namespace, it shows that the raise_amount attribute was created specifically for this instance, demonstrating how instance variables can be unique to each object.
  • The importance of understanding the distinction between instance and class variables is emphasized; different results may arise depending on whether self.raise_amount or Employee.raise_amount is used in methods.
  • Using self.raise_amount allows individual instances to have their own raise amounts while still enabling subclasses to override these values if necessary.

Tracking Class-wide Attributes

  • A new example illustrates tracking the total number of employees as a class variable (num_of_employees) initialized at zero, which should remain consistent across all instances.
  • Each time a new employee is instantiated, the class variable increments by one within the __init__ method, ensuring that it reflects the total count accurately.
  • It’s crucial to use Employee.num_of_employees, rather than self.num_of_employees, since there’s no scenario where individual instances would need differing employee counts.

Practical Demonstration and Conclusion

  • After running tests with print statements before and after instantiation, it confirms that the total number of employees correctly updates based on how many were created (e.g., returning 2 after two instantiations).
Video description

In this Python Object-Oriented Tutorial, we will be learning about class variables. We will see how they differ from instance variables and also some ideas for exactly how we would want to use them. 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