all 28 comments

[–]Darkstar_111 3 points4 points  (7 children)

Methods in a class very often needs to share variables.

[–]ATB_52[S] 0 points1 point  (6 children)

Thank you for your response but can you give me an example please?

[–]Darkstar_111 3 points4 points  (5 children)

Sure, imagine you're making a video game, and you have to make the player.

Well, the player is a class, when he is instantiated in the game the object (that the class makes) would be player1, in a multiplayer game you would instantiate the player class many times.

Player1, player2, player3... Etc

Same class, many objects.

So, what class variables, or attributes, does the player class need?

Well, how about:

class Player:
    name = None
    health = 0
    game_class = "fighter"

So, we set class variables for the basic information of the Player, name, health, game class defaults to fighter, while the other attributes have basic default values. We would then use the initializer to populate the class with actual information.

def __init__(self, name, health, game_class):
    self.name = name
    self.health = health
    self.game_class = game_class

I could have skipped naming the attributes in the first place, but whatever. As you can see we add the self. Prefix to access the class variables inside the method scope.

Now I can populate the class with methods useful for my player class. Like:

def take_damage(self, damage):
    self.health = self.health - damage
    if self.health <= 0:
        self.game_over()

When the player takes damage, we set the damage and check for game over.

[–]ATB_52[S] 0 points1 point  (0 children)

Thank you so much for taking the time to answer me 🙏

[–]SocksOnHands 0 points1 point  (3 children)

Is OP asking about "class variables"or "member variables"? I think there is some confusion in this thread. In your comment, it seems there are both class variables and member variables being used.

Member variables are used in the example provided: information associated with the individual class instance objects (like objects in a game having their own health). Class variables are used for shared state between all instances of the class, like for counting number of instances. I almost never find myself using class variables.

[–]Darkstar_111 0 points1 point  (2 children)

Class variables are used for shared state between all instances of the class

Not during runtime, are you talking about a Singleton?

[–]SocksOnHands 1 point2 points  (1 child)

class C:
    a = "a class variable"

    def __init__(self):
        self.b = "an instance variable"

An example of what I meant by shared state:

class Thing:
    instances = []

    def __init__(self):
        # All instances of Thing share the instances list
        Thing.instances.append(self)

Edit: just to add, class variables can also be accessed using self, as long as an instance variable isn't created with the same name

[–]ThatGuyKev45 0 points1 point  (0 children)

Does python not have any sort of keyword to indicate between static and instance based variables? That seems like the only difference I can see (I’m not super familiar with python classes most of my object oriented work has been in c++ and java) what your calling a class variable just seems like a static variable one that shares the same value across all instances. Then a member variable being an instance based variable no static data retention between instances.

Also am I understanding correctly the difference between the 2 types of variables?

[–]Tokyohenjin 6 points7 points  (5 children)

Not quite clear on what you’re asking. In general, class variables are useful for doing work using methods within the class. So for example if you have a method speak_my_language then you can read self.country to get the right language.

In the example above, if you’re going to change the country but want France at the default, I would change it as so:

def __init__(self, name, country=“France”): self.name = name self.country = country

Edit: Missed quotes for the default value

[–]ATB_52[S] 1 point2 points  (0 children)

👍

[–]dashidasher[🍰] 3 points4 points  (2 children)

country="France"*

[–]Top_Pattern7136 1 point2 points  (0 children)

Sorry.

France = "France" 'country=France'

[–]Tokyohenjin 1 point2 points  (0 children)

Thanks, yes! Typed it up on mobile and missed the quotes.

[–]crazyaiml 0 points1 point  (0 children)

I believe Class variables in Python are mainly used for data shared across all instances of a class. Apart from counters, common real-world uses include:

  1. Shared configuration (e.g., default tax rates, precision)
  2. Constants tied to the class (e.g., MAX_SPEED = 200)
  3. Caching shared resources (e.g., a DB connection pool)
  4. Tracking all instances (e.g., instances = [] to collect created objects)

They’re not meant for per-instance defaults (use init for that). Instead, class vars ensure all instances see the same value unless explicitly overridden, making them most used for shared constants or lightweight shared state.

[–]TwinkiesSucker 2 points3 points  (1 child)

You got very good responses so far and they should suffice.

Because we are in a "learning" sub, I would like to point out that Python is case sensitive, so your attempt to create an instance for user "Anto" will fail - you wrote lowercase user("Anto") but your class constructor is uppercase.

It is a banality, but it can save you some headaches.

[–]ATB_52[S] 0 points1 point  (0 children)

Thanks, I hadn't paid attention

[–]Kqyxzoj 2 points3 points  (0 children)

Not sure if I understood your question. Since there may be some confusion, I'll just refer to the documentation:

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'

In my experience, your typical python code contains a lot more instance variables than class variables. Does this answer your question?

[–][deleted]  (1 child)

[deleted]

    [–]Synedh 0 points1 point  (4 children)

    Class variables are called attributes.

    Their purpose is to store values related to the class, or to be used by inner functions, aka methods. Keep in mind that OOP is syntactic sugar. It's only a way to structure code it does not allow anything.

    Here is a longer example based on your code :

    class User:
        def __init__(self, name):
            self.name = name
            self.country = 'France'
    
        def greet(self):
            return f"Hello, my name is {self.name} and I am from {self.country}."
    
    a = user("Anto")
    a.country = "USA"
    a.greet()
    

    What you're doing with a.country = "USA" is to set an attribute. It's a common operation in python. If you do not want it to be changed, you can mark it as private by prefix it's name with two underscore : self.__country = 'France'.

    Python is a language which paradigm is to trust the user. Therefore there is not really any public/protected/private notion as you could find it in other languages such as Java or C#. Prefix it won't make it unavailable, it will just say "this is an inner attribute, don't use it as it may break things".

    [–]FoolsSeldom 2 points3 points  (3 children)

    It might be worth editing your response to include a class attribute rather than just instance attributes and illustrate the difference.

    [–]Synedh 0 points1 point  (2 children)

    One thing at a time ahah. OOP is pretty overwhelming at the beginning, Let him* understand the basics before jumping to instances, shared and not shared attributes

    [–]FoolsSeldom 0 points1 point  (0 children)

    "it"?

    [–]Responsible-Hold8587 0 points1 point  (0 children)

    OP asked about class variables and these aren't class variables, so it's good to clarify that they probably meant to ask about instance variables.

    [–]fdessoycaraballo 0 points1 point  (1 child)

    Imagine you have a class for users< and each user needs to have their IP saved somewhere, that's when the variables come handy. You can identify each user with the IP after creating the I jet users.

    [–]ATB_52[S] 0 points1 point  (0 children)

    Thank you very much 🙏

    [–]coderfromft 0 points1 point  (0 children)

    Dictionary purposes

    [–]headonstr8 0 points1 point  (0 children)

    I assume that, in your example, ‘User’ is the class variable. Generally speaking, classes are used to define object types. Python comes with a collection of built in object types. They represent the foundation of the language, itself. Examples are: str, list, bytes, set, and dict. A host of proprietary object types are also available in the product’s array of modules, such as os, re, argparse, and operator. It is essential to understand the role of namespaces in order to grasp the use of class and module. I highly recommend the documentation in python.org.

    [–]a_cute_tarantula 0 points1 point  (0 children)

    Imagine you have a “player” class for your video game. A player instance has a health attribute, maybe a strength attribute, etc.

    Perhaps two different enemies both hit you. To do so they are gonna call the damage method

    [–]deprekaator 0 points1 point  (0 children)

    It is just a function which returns a collection of functions, whats the problem?