Published on

Python class variable and instance variable

Authors
  • avatar
    Name
    Lif
    Twitter

Below is the code of future in asyncio.

class Future:

    # Class variables serving as defaults for instance variables.
    _state = _PENDING
    _result = None
    _exception = None
    _loop = None
    _source_traceback = None
    _cancel_message = None

	def __init__(self, *, loop=None):
        """Initialize the future.

        The optional event_loop argument allows explicitly setting the event
        loop object used by the future. If it's not provided, the future uses
        the default event loop.
        """
        if loop is None:
            self._loop = events._get_event_loop()
        else:
            self._loop = loop
        self._callbacks = []
        if self._loop.get_debug():
            self._source_traceback = format_helpers.extract_stack(
                sys._getframe(1))
                

We can find two variable named _loop.

The first is class variable, second is self._loop which is called instance variable.

Class variables share the same value across all instances of the entire class.

Instance variables are variables that are owned independently by an instance of each class.

We can use class.variable to invoke class variables, and instance.variable to invoke instance variables.

Just like this:

class_loop = Future._loop
ins = Future()
ins_loop = ins._loop

Here is a sample code:

class TestClass:
    _flag = 1
    
    def __init__(self) -> None:
        # self._flag = 2
        pass

print(TestClass._flag)
c = TestClass()
print(c._flag)