Automatically update attributes of a class ?

3 次查看(过去 30 天)
Hi everyone.
I have a class called "Rect" (rectangle) which has 4 attributes: lenght (l), breadth (b), area (A) and perimeter (P). I wish to initialize the class using only the length and breadth and I want it to calculate the area and perimeter automatically. Later when I change its length or breadth I want the class to update the value of its area and perimeter automatically. I have been able to do this in python using the "@property" syntax as I have shown below:
class Rect:
def __init__(self, _l, _b):
self.l= _l #lenght
self.b= _b #breadth
pass
@property
def A(self): #area of rectangle
return self.l*self.b
@property
def P(self): #perimeter of rectangle
return 2*(self.l+self.b)
Following is an example of object in python:
rect_1= Rect(2, 3)
print(rect_1.A)
6
rect_1.l= 3
print(rect_1.A)
9
I wish to do exactly this in MATLAB, is there any equivalent?

采纳的回答

Matt J
Matt J 2020-7-28
编辑:Matt J 2020-7-28
This has to go in a file called Rect.m :
classdef Rect
properties
l,b
end
properties (Dependent,Hidden)
A,P
end
methods
function obj=Rect(l,b)
obj.l=l; obj.b=b;
end
function A=get.A(obj)
A=obj.l*obj.b;
end
function P=get.P(obj)
P=obj.l+obj.b;
end
end
end
and now you would do
>> rect_1= Rect(2, 3); rect_1.A
>> rect_1.l= 3; rect_1.A
  2 个评论
Matt J
Matt J 2020-7-28
You're welcome, but please Accept-click the answer to indicate so.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by