Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

oop - Matlab - Handle object properties of unique objects refer to the same object?

I am confused on how to use handle objects as properties in matlab. For example, I defined the following classes:

classdef Page < handle
properties
    word1;
    word2;
end

classdef Book < handle
properties
    page1 = Page;
    page2 = Page;
end

Now I instantiate two books:

iliad = Book;
odyssey = Book;

If I check if iliad and odyssey are the same:

eq(iliad, odyssey)

I get:

ans = logical 0

So far so good

But if I check if page1 of iliad and odyssey are the same:

eq(iliad.page1, odyssey.page1)

I get:

ans = logical 1

This is not good! It means that if I change page1 of odyssey, page1 of iliad will also change. What am I misunderstanding? How do I deal with this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This appears to be related to how MATLAB evaluates property default values. Per the documentation for Properties Containing Objects:

MATLAB? evaluates property default values only once when loading the class. MATLAB does not reevaluate the assignment each time you create an object of that class. If you assign an object as a default property value in the class definition, MATLAB calls the constructor for that object only once when loading the class.

It goes on to further note that:

Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create an instance of the class.

Which describes the equality you're seeing between books. MATLAB essentially caches class definitions, so while your Page objects are different within the book, they're going to be the same across books because MATLAB is only constructing the defaults once.

To avoid this, you can instantiate your Page objects in Book's constructor:

classdef Book < handle
properties
    page1
    page2
end

methods
    function self = Book()
        self.page1 = Page;
        self.page2 = Page;
    end
end
end

Which gives you the desired behavior:

>> iliad = Book;
>> odyssey = Book;
>> eq(iliad.page1, odyssey.page1)

ans =

  logical

   0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...