首页 > 解决方案 > 使用类中的函数编辑初始化部分时出现问题

问题描述

这是我当前的代码

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.weightsinitalize_weights(self)但是每当我为这个类分配一些东西并要求权重时,它只会告诉我None并忽略我的初始化权重:

x = MCP()
print(x.weights)

>> None

标签: pythonclass

解决方案


您声明了一个名为的函数这一事实实际上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]

推荐阅读