python - 使用类中的函数编辑初始化部分时出现问题
问题描述
这是我当前的代码
class MCP():
def __init__(self, features=4, labels=3, epochs=250):
self.f = features
self.l = labels
self.N = epochs
self.weights = None
def initialize_weights(self):
weights = np.zeros(4)
return weights
我想用 编辑self.weights
,initalize_weights(self)
但是每当我为这个类分配一些东西并要求权重时,它只会告诉我None
并忽略我的初始化权重:
x = MCP()
print(x.weights)
>> None
解决方案
您声明了一个名为的函数这一事实实际上initialize_weights
并没有使它初始化权重。你需要调用它。像这样:
class MCP():
def __init__(self, features=4, labels=3, epochs=250):
...
self.weights = self.initialize_weights() # <----
def initialize_weights(self):
weights = np.zeros(4)
return weights
请注意,这忽略了在程序中进一步初始化权重的要点。如果您希望在进行一些计算后能够初始化权重,您应该更改方法以更改状态而不是返回:
class MCP():
def __init__(self, features=4, labels=3, epochs=250):
...
self.weights = None
def initialize_weights(self):
self.weights = np.zeros(4)
现在一个程序可能如下所示:
x = MCP()
print(x.weights)
>> None
x.initialize_weights()
print(x.weights)
>> [0, 0, 0, 0]
# do some stuff with the object and change its weights
x.initialize_weights()
print(x.weights)
>> [0, 0, 0, 0]
推荐阅读
- html - 链接与孩子的大小不同
- sql - 在签出另一项之前签出一项的客户的 SQL 查询
- angular - 如何在 Angular 的应用程序级别设置自动完成“关闭”?
- android - 如何让 Android 10+ 用户从我的应用程序的下载文件夹中导入 zip 文件?
- javascript - Bootstrap V5 & jQuery:再次打开模态框时关闭事件不返回
- r - 是否可以拆分相关框以显示pairplot中两种不同处理的相关值?
- c++ - 在初始化数组中插入字符
- elasticsearch - 弹性转换错误 (Elasticsearch 7.13.3)
- exchangewebservices - Exchange EWS Web 应用程序的问题
- vba - 如何使我的 VBA 用户窗体“半模态”?