我试图添加numpy数组元素的值,但我不知道形状,直到添加第一个元素,所以我用if
语句编写了以下工作代码:
import numpy as np
class Layer:
def __init__(self):
self.delta_weights = np.array([])
def add_delta_weights(self, delta_weights):
if(self.delta_weights.size > 0):
self.delta_weights = self.delta_weights + delta_weights
else:
self.delta_weights = delta_weights
我想知道如果没有if
语句,是否有更好的方法来编写上面的代码?我如何初始化self.delta_weights
,这样我就可以简单地写:
def add_delta_weights(self, delta_weights):
self.delta_weights = self.delta_weights + delta_weights
一般来说,未初始化状态是不好的做法。这就是构造函数的作用,对象的存在意味着它的状态是有效的。
进一步阅读
你可以使用构造函数使它干净:
import numpy as np
class Layer:
def __init__(self, delta_weights: np.array):
self._delta_weights = delta_weights
def add_delta_weights(self, other: np.array):
self._delta_weights += other
layer = Layer(weights)
的存在意味着内部状态是有效的。
用法:
layer = Layer(np.zeros((5, 6, 7))) # 1st call
layer.add_delta_weights((np.zeros((5, 6, 7)))) # consecutive calls
layer.add_delta_weights((np.zeros((5, 6, 7)))) # consecutive calls
layer.add_delta_weights((np.zeros((5, 6, 7)))) # consecutive calls
我假设你的包装逻辑有一些"第一次调用"的感觉。和"连续呼叫">
一般来说,尽量避免使用if语句。