Property Setter and Getter MethodsProperty access methods execute specific code whenever the associated property's value is referenced or assigned a new value. These methods enable you to perform a variety of operations:
Property access methods execute automatically whenever you set or query the corresponding property values from outside the access method. MATLAB? never calls the set method for a property of a particular class if the property value is set from within that set method. Similarly, the get method for a property of a particular class is never called if the property is queried from within that get method. Restrictions on Access MethodsYou can define property access methods only:
MATLAB has no default set or get property access methods. Therefore, if you do not define property access methods, MATLAB software does not invoke any methods before assigning or returning property values. Once defined, only the set and get methods can set and query the actual property values. See Set Method Behavior for information on cases where MATLAB does not call property set methods.
Access Methods Cannot Call Other Functions to Access Property ValuesYou can set and get property values only from within your property set or get access method. You cannot call another function from the set or get method and attempt to access the property value from that function. For example, an anonymous function that calls another function to do the actual work cannot access the property value. Similarly, an ordinary access function cannot call another function to access the property value. Defining Access MethodsAccess methods have special names that include the property's name. Therefore, get.PropertyName executes whenever PropertyNameis referenced and set.PropertyName executes whenever PropertyName is assigned a new value. Define property access methods in a methods block that specifies no attributes. You cannot call these methods, MATLAB calls them when any code accesses the properties. Therefore, property access methods do not appear in the list of class methods returned by the methodscommand and are not included in the meta.class object's Methods property. However, the meta.property object's SetMethod property contains a function handle to the property's set method and the GetMethod property contains a function handle to the property's get method. For example, if the class myClass defines a set function for its Text property, you can obtain a function handle to this method from themeta.class object: m = ?myClass; m.Properties{1}.SetMethod % Assuming Text is the first property in the cell array ans = @\mydir\@myClass\myClass.m>myClass.set.Text % This is a function handle The meta.class object (m) contains meta.property objects corresponding to each class property in its Properties property. This example assumes that the Text property corresponds to the first meta.property object in the cell array of meta.property objects. The order of the class properties in the meta.class Properties property is the same as the order in which the class definition defines the properties. Class Metadata provides more information on using meta-classes. Function handles discusses the use of function handles. Property Set MethodsProperty set methods have the following syntax, where PropertyName is the name of the property. methods % No method attributes function obj = set.PropertyName(obj,value) % Value class end Here obj is the object whose property is being assigned a value and value is the new value that is assigned to the property. Value class set functions must return the object with the new value for the property assigned. Value classes replace the object whose property is being assigned with the object returned by the set method. Handle classes do not need to return the modified object. methods % No method attributes function set.PropertyName(obj,value) % Handle class end The property set method can perform actions like error checking on the input value before taking whatever action is necessary to store the new property value. function obj = set.PropertyName(obj,value) if ~(value > 0) error('Property value must be positive') else obj.PropertyName = value; end end See Restricting Properties to Specific Values for an example of a property set method. Set Method BehaviorIf a property set method exists, MATLAB calls it whenever a value is assigned to that property. However, MATLAB does NOT call property set methods in the following cases:
When assigning a property value, the calling function's copy of the object that has been passed to the set method reflects the changed value. Therefore, an assignment to even a single property is able to affect the whole object. This behavior enables a set method to change other properties in the object as well as its designated property. For example, a graphics window object can have a Units property and a Size property. Changing the Units property can also require a change to the values of the Size property to reflect the new units. Property Get MethodsMATLAB calls a property's get method whenever the property value is queried. For example, passing a property value in the following statement causes the method get.XYData to execute, if it exists. plot(obj.XYData) Property get methods have the following syntax, where PropertyName is the name of the property. The function must return the property value. methods % No method attributes function value = get.PropertyName(obj) end Get Method BehaviorMATLAB does NOT call property get methods in the following cases:
Set and Get Methods for Dependent PropertiesDependent properties do not store data because the value of a dependent property depends on the current state of something else, like a concrete property value. Dependent properties must define a get method to determine the value for the property, when queried. Typically, the property get method queries other property values to determine what value to return for the dependent property. For example, the Account class returns a value for the dependent Balance property that depends on the value of the Currency property. The get.Balance method queries the Currency property before calculating a value for the Balance property. MATLAB calls the get.Balance method when the Balance property is queried. You cannot call get.Balance explicitly. Here is a partial listing of the class showing a dependent property and its get method: classdef Account properties Currency DollarAmount end properties (Dependent) Balance end ... methods function value = get.Balance(obj) c = obj.Currency; switch c case 'E' v = obj.DollarAmount / 1.3; case 'P' v = obj.DollarAmount / 1.5; otherwise v = obj.DollarAmount; end format bank value = v; end end end Get Method for Dependent PropertyOne application of a property get method is to determine the value of a property only when you need it, and avoid storing the value. To use this approach, set the property's Dependent attribute to true: properties (Dependent = true) PropertyName end Now the get method for the PropertyName property determines the value of that property and assigns it to the object from within the method: function value = get.PropertyName(obj) value = calculateValue; ... end The get method calls a function or static method calculateValue to calculate the property value and returns value to the code accessing the property. The property get method can take whatever action is necessary within the method to produce the output value. Using a Dependent Property provide an example of a property get method. When to Use Set Methods with Dependent PropertiesWhile a dependent property does not store its value, there are situations in which you might want to define a set method for a dependent property. For example, suppose you have a class that changes the name of a property from OldPropName to NewPropName. You want to continue to allow the use of the old name without exposing it to new users. You can make OldPropName a dependent property with set and get methods as show in the following example: properties NewPropName end properties (Dependent, Hidden) OldPropName end methods function obj = set.OldPropName(obj,val) obj.NewPropName = val; end function value = get.OldPropName(obj) value = obj.NewPropName; end end There is no memory wasted by storing both old and new property values, and code that accesses OldPropName continues to work as expected. It is sometimes useful for a set method of a dependent property to assign values to other properties of the object. Assignments made from property set methods cause the execution of any set methods defined for those properties. See Using a Dependent Property for an example. When to Use Private Set Access with Dependent PropertiesIf you use a dependent property only to return a value, then do not define a set access method for the dependent property. Instead, set theSetAccess attribute of the dependent property to private. For example, consider the following get method for the MaxValue property: methods function mval = get.MaxValue(obj) mval = max(obj.BigArray(:)); end end This example uses the MaxValue property to return a value that it calculates only when queried. For this application, define the MaxValueproperty as dependent and private: properties (Dependent, SetAccess = private) MaxValue end Set and Get Method Execution and Property EventsMATLAB software generates events before and after set and get operations. You can use these events to inform listeners that property values have been referenced or assigned. The timing of event generation is as follows:
If a class computes a property value (Dependent = true), then the behaviors of its set events are like the get events:
If a property is not computed (Dependent = false, the default), then the assignment statement with the set method generates the events:
Events and Listeners — Concepts provides general information about events and listeners. Creating Property Listeners provides information about using property events. The PostSet Event Listener shows an example of a property listener. Create a Property Set Listener is another example that uses property events. Access Methods and Subscripted Reference and AssignmentUse subscripting as a way to reference or assign property values (that is, a = obj.prop(6) or obj.prop(6) = a) without interfering with property set and get methods. When using subscripted reference, the get method returns the whole property value and MATLAB accesses the value referenced by subscripting that object. For subscripted assignment, MATLAB:
MATLAB always passes scalar objects to set and get methods. When reference or assignment occurs on an object array, the set and get methods are called in a loop. See Assigning to Read-Only Properties Containing Objects for related information. Performing Additional Steps with Property Access MethodsProperty access methods are useful in cases where you want to perform some additional steps before assigning or returning a property value. For example, the Testpoint class uses a property set method to check the range of a value. It then applies scaling if it is within a particular range, and set it to NaN if it is not. The property get methods applies a scale factor before returning its current value: classdef Testpoint properties expectedResult = []; end properties(Constant) scalingFactor = 0.001; end methods function obj = set.expectedResult(obj,erIn) if erIn >= 0 && erIn <= 100 erIn = erIn.*obj.scalingFactor; obj.expectedResult = erIn; else obj.expectedResult = NaN; end end function er = get.expectedResult(obj) er = obj.expectedResult/obj.scalingFactor; end end end |
|
来自: windycityboy > 《class》