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

Matlab构造函数内无法修改类属性?是Bug还是设计意图?

这不是Bug,是Matlab值类的设计特性!

你的问题核心在于Matlab值类(Value Class)的工作机制——值类的方法默认操作的是对象的副本,而非原对象本身。如果不把方法返回的修改后对象赋值回self,所有属性更改都会直接丢失。

具体问题拆解

看你的代码,这几处都没正确处理值类的返回赋值逻辑:

  1. 构造函数里调用self.calculateCalculatedProperties();,没有接收方法返回的修改后对象;
  2. calculateCalculatedProperties方法里调用self.Velocity();和self.Length();,同样没把这两个方法返回的对象赋值回self;
  3. 虽然你的Velocity和Length方法都声明了返回self,但调用时没赋值,等于做了无用功。

修正后的完整代码

classdef piping 
%PIPING Summary of this class goes here 
% Detailed explanation goes here 
properties 
    flowRate 
    diameter 
    startLocation 
    location  % 注意你原代码重复定义了location属性,这里去掉重复项
    endLocation 
end 
methods 
    function self = piping(flowRate, diameter, startLocation, endLocation) 
        self.flowRate = flowRate; 
        self.diameter = diameter; 
        self.startLocation = startLocation; 
        self.endLocation = endLocation; 
        % 关键:接收方法返回的修改后对象
        self = self.calculateCalculatedProperties(); 
    end 
    function self = calculateCalculatedProperties(self) 
        fprintf("hey\n") 
        % 关键:把每个方法返回的对象赋值回self
        self = self.Velocity(); 
        self = self.Length(); 
    end 
    function self = Velocity(self) 
        self.velocity = self.flowRate / (pi * self.diameter^2 / 4); 
    end 
    function self = Length(self) 
        % 原代码中location未初始化,这里假设你是想调用全局的calculateDistance函数
        self.length = calculateDistance(self.startLocation,self.endLocation) ; 
        fprintf("hey this is lengthhhh\n") 
        self.flowRate = 10000000; 
    end 
end 
properties % Calculated properties 
    velocity 
    length 
end 
end

额外优化方案:改用句柄类

如果不想每次都手动赋值返回对象,你可以把piping类改成句柄类——只需让它继承handle类即可:

classdef piping < handle
% 剩下的代码完全不变,方法里不需要返回self,修改会直接作用于原对象
end

句柄类是按引用传递的,方法内部修改对象属性会直接反映到原对象上,无需额外的返回赋值操作。

总结一下:你的问题完全是Matlab类系统的设计特性,不是Bug,只要遵循值类的规则(返回并赋值修改后的对象),或者改用句柄类就能解决。

内容的提问来源于stack exchange,提问作者RedGermen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:32:38