0
class Matrix:

    decimals = True

    def __init__(self, decimals=decimals):

        if decimals:
            print('The matrix will have decimal values.')
        else:
            print('The matrix will have float values.')


Matrix.decimals = False
mat1 = Matrix()

Output:

The matrix will have decimal values.

I'm trying to make it to where I can change the value of decimals for all instances of a class while also using it as an argument in the __init__ method. Why is the above not working?

Gabe Morris
  • 804
  • 4
  • 21
  • 2
    It does not work because default values are defined (and set) at **function/method** definition time. When you set `Matrix.decimals = False`, `__init__.decimals`'s value is already set to `True` – DeepSpace Mar 15 '21 at 16:47
  • 1
    In hindsight, that duplicate is probably not the best. If someone finds a better one, feel free to replace – DeepSpace Mar 15 '21 at 16:50

1 Answers1

1

The default argument of __init__ is evaluated when the method is defined. At this point the value of the variable is still True.

If you want the class variable to be evaluated when the method is called, it needs to be done inside the method body:

class Matrix:

    decimals = True

    def __init__(self, decimals=None):
        if decimals is None:
            decimals = self.decimals

        if decimals:
            print('The matrix will have decimal values.')
        else:
            print('The matrix will have float values.')


Matrix.decimals = False
mat1 = Matrix()

Output:

The matrix will have float values.
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Thank you. That suggested question is different than what I am asking here. It deals more with the scope of inheritance, while my question here deals with the scope of class attributes. – Gabe Morris Mar 15 '21 at 16:56