You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本报AttributeError无法识别类属性,Jupyter却正常运行

问题分析与解决

核心错误原因

你的代码里类的构造函数名称拼写错误:Python类的构造函数是__init__(前后各两个下划线),但你写成了__int__。这个错误的方法不会在实例化BasicNNTrain对象时自动执行,导致self.w00、self.b00等所有类属性都没有被初始化,所以调用model(input_doses)时会抛出AttributeError。

Jupyter环境看似正常的原因

Jupyter的内核会保留当前会话中的变量和类定义缓存。如果你之前在Jupyter中运行过构造函数正确的版本,后续修改代码后没有重启内核,错误的类定义不会覆盖之前正确的缓存,所以看起来代码能正常运行。而.py文件是从头开始执行,没有缓存,错误会直接暴露。

修正后的代码

只需要把类中的构造函数名称修正即可:

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD

import matplotlib.pyplot as plt
import seaborn as sns


class BasicNNTrain(nn.Module):
    def __init__(self):  # 修正构造函数名称
        super().__init__()
        self.w00 = nn.Parameter(torch.tensor(1.7), requires_grad=False)
        self.b00 = nn.Parameter(torch.tensor(-0.85), requires_grad=False)
        self.w01 = nn.Parameter(torch.tensor(-40.8), requires_grad=False)

        self.w10 = nn.Parameter(torch.tensor(12.6), requires_grad=False)
        self.b10 = nn.Parameter(torch.tensor(0.0), requires_grad=False)
        self.w11 = nn.Parameter(torch.tensor(2.7), requires_grad=False)

        self.final_bias = nn.Parameter(torch.tensor(0.0), requires_grad=True)

    def forward(self, input):
        input_to_top_relu = input * self.w00 + self.b00
        top_relu_output = F.relu(input_to_top_relu)
        scaled_top_relu_output = top_relu_output * self.w01

        input_to_bottom_relu = input * self.w10 + self.b10
        bottom_relu_output = F.relu(input_to_bottom_relu)
        scaled_bottom_relu_output = bottom_relu_output * self.w11

        input_to_final_relu = scaled_top_relu_output + scaled_bottom_relu_output + self.final_bias

        output = F.relu(input_to_final_relu)

        return output


model = BasicNNTrain()
for name, param in model.named_parameters():
    print(name, param.data)

input_doses = torch.linspace(start=0, end=1, steps=11)
print(input_doses)

model(input_doses)

内容的提问来源于stack exchange,提问作者M a m a D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:27:22