Search code examples
pythonstatic-methodsclass-method

Can I access an instance-variable using a @classmethod?


class MyClass:
    __module_attr: str = "module text value"

    def __init__(self):
        self.__instance_attr: str = "instance text value"

    @classmethod
    def cls_modify(cls):
        cls.__module_attr = "class text value"

    @classmethod
    def cls_display(cls):
        print(cls.__module_attr)

Suppose, I want to print the value of __instance_attr inside cls_display().

How can I do that?


Solution

  • No. The class method is not given a reference to the instance object so its data is unavailable. Python generates the first parameter for instance and class methods for you. For instance methods, its a reference to instance data. For class methods, its a reference to the class object itself. If you don't need either of those things, static methods don't get any special first parameter.

    In all three cases, the call looks the same. Nothing special is needed by the caller to tell you the method type. The caller need not know. And this is the point of the different types. The implementer chooses the type based on the data that's needed, but doesn't have to bother the user about it.