Global variable

whats the meaning for declaring variable like this…

def calculate_total_amounts(self):
self.total_hours = 0.0
self.total_billable_hours = 0.0

need one global variable to be accessible in different function, whats the recommended practice for the same.

For that you have to create one class variable

1 Like

If you need a variable that can be used in different functions within the same class, you should declare it with self. This makes it an instance variable, meaning each instance of the class has its own copy of the variable.

Example:

class ClassXYZ:
    def __init__(self):
        self.variable_a = 0.0

    def first_method(self):
        self.variable_a += 1.0

    def second_method(self):
        print(self.variable_a)

If you need a variable shared across all instances of a class, use a class variable:

Example:

class ClassXYZ:
    shared_variable = 0.0

    def first_method(self):
        MyClass.shared_variable += 1.0

    def second_method(self):
        print(ClassXYZ.shared_variable)

Instance variables are usually the best choice for most needs.

1 Like