Scope of Class Variables?

Viewed 33

Hello I have a module that is installed in site-packages folder. The module contains a class that mostly consists of class variables and static methods (there are no instance methods), something of the form

class C1:

    name = 'C1'
    todos = []
    tasks = {}

    @classmethod
    def f1(cls) -> None:
        pass

    @staticmethod
    def f2(cls) -> None:
        pass

etc. The class variables as well as the lists and dicts are manipulated in the methods. Now I see another class (lets say C2) (also in site-pacakges) that uses this class C1. Now C2 is used as a base class for other classes. My question is: Will these class variables in C1 shared by all those class instances?

I an unable to understand the scoping. Can somebody please guide me to a good example.

1 Answers

Yes, those values will be shared across C1 instances, they are class attributes. You use them using the class name and then the attribute:

C1.name  # "C1"

However, you can override the value for a single instance by using self:

# Inside of a method
self.name = "A particular C1"

Also, when using inheritance, the class attribute will still be accessible through the subclass:

class Super:
    name = "Super"

class Sub(Super):
    pass

print(Super.name)  # Super
print(Sub.name)  # Super
Related