Is it possible to add methods on the fly to MATLAB classes?

前端 未结 3 1906
攒了一身酷
攒了一身酷 2021-02-08 15:50

Writing a subclass of dynamicprops allows to me to add properties dynamically to an object:

addprop(obj, \'new_prop\')

This is gre

3条回答
  •  抹茶落季
    2021-02-08 16:35

    I'm adding this answer because I think that this is not intuitive. At least not to myself at this moment. After finding this question I thought I had what I needed to be able to define the set/get methods for my dynamic class. All I wanted to achieve with this was something similar to what python does with its __setattr__ method. In any case, here is a continuation of the class made by @jonas a while ago with a few modifications to add the our custom set method.

    classdef myDynamicClass < dynamicprops
        properties (Hidden)
            name_ %# class name
        end
        methods
            function self = myDynamicClass(clsname, varargin)
                % self = myDynamicClass(clsname, propname, type)
                % here type is a handle to a basic datatype.
                self.name_ = clsname;
                for i=1:2:length(varargin)
                    key = varargin{i};
                    addprop(self, key);
                    prop = findprop(self, key);
                    prop.SetMethod = makefunc(key, varargin{i+1});
                end
            end
            function out = classname(self)
                out = self.name_;
            end
        end
    end
    
    function h = makefunc(key, argtype)
        h = @newfunc;
        function newfunc(obj, val)
           obj.(key) = argtype(val); 
        end
    end
    

    With this class I'm defining the set method so that the parameter passed to the attribute is copied to the right type. To see what I mean consider the following usage:

    >> p_int = myDynamicClass('Point', 'x', @int8, 'y', @int32);
    >> p_int.x = 1000 
    
    p_int = 
    
      myDynamicClass with properties:
    
        y: []
        x: 127
    
    >> class(p_int.x)
    
    ans =
    
    int8
    

    With this we have forced the x attribute to be an integer of 8 bits which can only hold integers from -128 to 127. Also notice how the class of each attribute gives us the intended type.

提交回复
热议问题