Sobes.tech
Junior — Middle

How is a variable declared inside a class?

sobes.tech AI

Answer from AI

In Python, a variable inside a class is declared either as a class attribute or as an instance attribute.

  • A class attribute is declared directly within the class body and is shared among all instances:
class MyClass:
    class_variable = 10  # class attribute
  • An instance attribute is declared inside a method, usually in the constructor __init__, and belongs to a specific object:
class MyClass:
    def __init__(self, value):
        self.instance_variable = value  # instance attribute

Thus, declaring a variable inside a class depends on whether a common attribute for all objects is needed or an individual one for each instance.