Matlab-处理唯一对象的对象属性是指同一个对象吗? [英] Matlab - Handle object properties of unique objects refer to the same object?

查看:46
本文介绍了Matlab-处理唯一对象的对象属性是指同一个对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何在Matlab中将句柄对象用作属性感到困惑.例如,我定义了以下类:

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

现在我实例化两本书:

iliad = Book;
odyssey = Book;

如果我检查iliad和odyssey是否相同:

If I check if iliad and odyssey are the same:

eq(iliad, odyssey)

我得到:

ans = logical 0

到目前为止一切顺利

但是,如果我检查iliad和奥德赛的page1是否相同:

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

eq(iliad.page1, odyssey.page1)

我得到:

ans = logical 1

这不好!这意味着,如果我更改奥德赛的page1,则iliad的page1也将更改.我有什么误会?我该如何处理这个问题?

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?

推荐答案

这似乎与MATLAB评估属性默认值的方式有关.根据包含对象的属性的文档:

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

MATLAB® 在加载时只计算一次属性默认值班级.每次创建时MATLAB不会重新评估分配该类的对象.如果将对象分配为默认属性类定义中的值,MATLAB为此调用构造函数加载类时只能对象一次.

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:

仅在以下情况下才对属性默认值进行评估:第一次需要,并且在MATLAB首次初始化类时仅一次.每次创建MATLAB时,MATLAB不会重新评估表达式该类的实例.

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.

其中描述了您在书籍之间看到的平等.MATLAB本质上缓存类定义,因此当您书中的 Page 对象是不同的,由于MATLAB仅会构造一次默认值,因此各本书中的对象将是相同的.

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.

为避免这种情况,您可以在 Book 的构造函数中实例化 Page 对象:

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

这篇关于Matlab-处理唯一对象的对象属性是指同一个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆