DEV Community

James Hubert
James Hubert

Posted on

2

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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay