首页 > 解决方案 > 为什么 Matlab 会更改作为主对象属性的所有对象的值?

问题描述

在更改设置为其他对象属性的对象的属性时,我无法理解 Matlab 的行为。具体来说,假设我有三个对象: a parentObject、 achildObject和 a propertyObject。当然,在这个简单的例子中,这些属性似乎有点荒谬,但我正在编写一个相当大的程序,在这些级别上对所有相应的方法和属性进行分组是很有用的。

现在,我对这些类的定义如下所示。parentObject继承自允许dynamicprops它有一个交互式可编辑的子列表。propertyObject继承自,因为在我的dynamicprops程序中,我需要能够动态添加(或删除未使用的)属性。

classdef parentObject < dynamicprops
    properties
        name 
        children = [];
    end

    methods
        function obj = parentObject(name)
            obj.name = name;
        end
        function obj = addchild(obj, childName)
            obj.children = [obj.children, childObject(childName)];
        end
    end
end
classdef childObject
    properties
        name
        someProperty(1, 1) propertyObject
    end

    methods
        function obj = childObject(name)
            obj.name = name;
        end
    end
end
classdef propertyObject < dynamicprops

    properties
        value1 = 0;
        value2 = 0;
    end
    methods

    end
end

现在在下面的交互式会话中,我正在尝试创建子对象,并调整其中一个的默认值childrenObject之一propertyObject。我希望其中一个属性value1,改变。children

然而,情况并非如此(见下文)。更改其中一个孩子的propertyObject也会自动更改第二个孩子的propertyObject。更重要的是,测试这两个propertyObjects 是否相等会产生积极的结果。我希望孩子的实例化(以及它的默认值)每次都会propertyObject产生一个唯一的。propertyObject我来自 Python 编程,据我所知,这里就是这种情况。谁能向我解释我哪里出错了,以及如何让课程按照我的意图行事?

>> parent = parentObject('parent')

parent = 

  parentObject with properties:

        name: 'parent'
    children: []

>> parent.addchild('child1')

ans = 

  parentObject with properties:

        name: 'parent'
    children: [1×1 childObject]

>> parent.addchild('child2')

ans = 

  parentObject with properties:

        name: 'parent'
    children: [1×2 childObject]

>> parent.children(1).someProperty

ans = 

  propertyObject with properties:

    value1: 0
    value2: 0

>> parent.children(2).someProperty

ans = 

  propertyObject with properties:

    value1: 0
    value2: 0

>> parent.children(2).someProperty.value1 = NaN

parent = 

  parentObject with properties:

        name: 'parent'
    children: [1×2 childObject]

>> parent.children(1).someProperty.value1

ans =

   NaN

>> parent.children(1).someProperty == parent.children(2).someProperty

ans =

  logical

   1

Ps,我看到我的问题已被标记为重复。但是,重复的问题只回答了我的部分问题;解释我如何获得所需对象行为的位。即使重复的问题解释了 Matlab 仅加载一次默认对象/属性,我仍然不清楚为什么 Matlab 在主动更改一个实例的此默认值时会突然更改所有实例的属性值。也就是说,如果我们不能改变一个实例的默认值而不改变所有实例的值,那么默认的目的是什么?

标签: matlaboopobjectinstancedynamic-properties

解决方案


推荐阅读