DEV Community

James Hubert
James Hubert

Posted on

1

Intro to Python - Day 3 - Class Variables vs Instance Variables

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's lesson is a simple one yet presents an important milestone in the Object-oriented programming journey. It closely follows yesterday's tutorial on creating classes.

When creating a class in Python, you can either create a variable on the class or you can create an instance variable within the constructor function.

The difference is that class variables are defined on the entire class. When they're changed anywhere they are changed for every instance of the class. This makes them similar to a global variable, and very dangerous.

There may be rare instances where we want to create these, but in general in the wild you'll want to stick to instance variables 99% of the time. These are variables defined only on an instance of a class. When you change them for one instance of a class it doesn't have any effect on the other instances of that class.

In code it would look like this:

class Person:
    name = "James"

class Dog:
    def __init__(self):
        self.name = "Fido"
Enter fullscreen mode Exit fullscreen mode

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay