How to define attributes in a Python class?
In Python, class attributes can be defined anywhere within the class. Some common ways to do so include the following:
- Define properties inside a class.
- MyClass has two attributes: attr_1 with the value ‘value_1’ and attr_2 with the value ‘value_2’.
- Define attributes in the constructor of a class.
- MyClass is a class that has an initializer method (__init__) that assigns the values of attr_1 and attr_2 to the respective attributes of the class.
- Adding properties dynamically in a class method.
- The class MyClass has a method called set_attr that sets a specific attribute with a given value.
- Define properties using the @property decorator.
- MyClass is a class that has an attribute called _attr that can be accessed with the attr property and modified using the attr setter.
In the fourth way mentioned above, the attribute name starts with a single underscore (e.g. _attr), which is a common convention used to indicate that the attribute is private and not recommended to be accessed directly. The attribute can be accessed or modified through getter and setter methods.