DEV Community

James Hubert
James Hubert

Posted on

Intro to Python - Day 4 - Modifying a Class Variable from Within the Class Itself

Hi there. I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Today in one of the lessons I worked on for the fantastic backend development tutorial boot.dev for one lesson we were asked to modify a class variable from within a method.

This follows on closely to yesterday's blog post about classes and object oriented programming in Python.

It actually took me a bit of digging and eventually I just had to break down and ask ChatGPT to find the answer. Most of the documentation and blog posts out there only discuss changing a class variable from outside of the variable.

The answer is, to modify a class variable from within the class itself, you must use the name of the class itself.

For example, if I have a class called Company and a class variable on it called number_of_employees = 0. Say I have a method called hire_new_employee that takes in their name and position title, but also increments number_of_employees by 1:

class Company:
    number_of_employees = 0

    def __init__(self, company_name):
        self.company_name = company_name

    def hire_new_employee(self, name, position):
        self.name = name
        self.position = position
        Company.number_of_employees += 1
Enter fullscreen mode Exit fullscreen mode

As I show, you need to call the class itself and set the variable on it from within the class method, or wherever you are modifying the variable.

If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.

Top comments (0)