Python模板类类属性M修改后实例未生效问题求解
问题根源
你的代码里,matrix=np.ones((M,M))是在类定义阶段就执行完毕的,此时类属性M的值是0,所以matrix被初始化成了0×0的空数组。哪怕之后你把Example.M改成5,已经生成的matrix不会自动重新计算——它的初始化只在类第一次定义时运行一次。
解决方案
下面提供两种不需要把M改成实例属性的解决办法:
方法一:实例化时检查并更新类属性matrix
如果希望所有实例共享同一个matrix,且修改后保留状态,可以在__init__里先判断当前matrix的形状是否和最新的M匹配,不匹配就重新生成:
import numpy as np class Example(): M=0 matrix=np.ones((M,M)) def __init__(self,a,b): self.a=a self.b=b # 检查matrix形状是否符合当前M,不符合就重新初始化 if Example.matrix.shape != (Example.M, Example.M): Example.matrix = np.ones((Example.M, Example.M)) self.operate() def operate(self): Example.matrix = Example.matrix * self.a * self.b print(Example.matrix) Example.M=5 m1=Example(3,5)
运行这段代码会输出5×5的全15矩阵,符合需求。
方法二:用类属性的@property动态生成matrix
如果需要每次访问matrix时都基于当前M的值生成(或缓存修改后的状态),可以把matrix改成带缓存的类属性:
import numpy as np class Example(): M=0 # 用私有属性缓存matrix _matrix = None @classmethod @property def matrix(cls): # 如果缓存不存在,或者形状和当前M不匹配,重新生成 if cls._matrix is None or cls._matrix.shape != (cls.M, cls.M): cls._matrix = np.ones((cls.M, cls.M)) return cls._matrix # 给matrix加setter,方便修改缓存 @matrix.setter def matrix(cls, value): cls._matrix = value def __init__(self,a,b): self.a=a self.b=b self.operate() def operate(self): Example.matrix = Example.matrix * self.a * self.b print(Example.matrix) Example.M=5 m1=Example(3,5)
这种方式更灵活,哪怕后续再修改Example.M,下次访问matrix时会自动生成对应大小的新矩阵。
内容的提问来源于stack exchange,提问作者torunoglu
相关产品推荐
相关产品推荐

