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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

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

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay