我在Python中有一个带有getter和setter的类,我想将它转换为MATLAB

问题描述 投票:0回答:1

我怎么能把这段代码翻译成MATLAB?即使我使用getter和setter,那么如何在后一个函数中调用MATLAB中的getter函数呢?

class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        self._temperature = value
python matlab class setter getter
1个回答
2
投票

您不需要在MATLAB中为属性定义setter或getter。 MATLAB中类的转换如下所示:

classdef Celsius
    properties
        temperature = 0
    end
    methods
        function obj = Celsius(temperature)
            if nargin < 1
                return
            end
            obj.temperature = temperature;
        end

        function val = toFahrenheit(obj)
            val = obj.temperature * 1.8 + 32;
        end
    end
end

如果要隐藏属性的getter,可以添加GetAccess属性:

    properties (GetAccess = private) % or `SetAccess = private` to hide the setter, and `Access = private` to hide both the setter and getter
        temperature = 0
    end

要使用该类:

myCelsiusObject = Celsius(); % initialise the object with temperature = 0.
myCelsiusObject = celsius(10); % initiliase the object with temperature = 10.
currentTemperature = myCelsiusObject.temperature; % get the value of the temperature property.
currentFahrenheit = myCelsiusObject.toFahrenheit; % get fahrenheit.
myCelsiusObject.temperature = 1; % set the value of the temperature property to 1.

更多关于MATLAB中的getter和setter

MATLAB确实有吸气剂,但它们用于所谓的Dependent属性,其值在getter函数中自动计算。更多关于这一点,请参阅this documentation

MATLAB中的Setter可用于公共属性以验证输入值。见this documentation

如果您打算在MATLAB中进行面向对象编程,我还建议您阅读full documentation

© www.soinside.com 2019 - 2024. All rights reserved.