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()输出:
The matrix will have decimal values.我试图使它能够更改类的所有实例的decimals值,同时也可以在__init__方法中使用它作为参数。为什么上面的方法不起作用?
发布于 2021-03-15 16:46:45
定义方法时计算__init__的默认参数。此时,变量的值仍然是True。
如果要在调用方法时计算类变量,则需要在方法主体内执行:
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()输出:
The matrix will have float values.https://stackoverflow.com/questions/66642097
复制相似问题