Python Class Variables Declaration Guide

In Python, class variables can be declared directly in the class definition or using the self keyword in the class methods.

  1. Declare class variables directly in the class definition.
class MyClass:
    class_variable = "Hello"

print(MyClass.class_variable)  # 输出: Hello
  1. Declare the self keyword in a class method.
class MyClass:
    def __init__(self):
        self.class_variable = "Hello"

obj = MyClass()
print(obj.class_variable)  # 输出: Hello

Both methods can be used to declare class variables, but the class variables declared by method one are shared properties of the class, while the class variables declared by method two are properties of each object of the class.

bannerAds