我正在将一些代码从Python翻译到MatLab,并且我意识到它们在字典中存储元素的方式有所不同。比较这两段代码,我希望有人能证实我的看法:
在Matlab中,当请求字典中的值时,返回一个副本,而不是指针。因此,如果该值被修改,则字典中的值保持不变。
在Python中,当请求字典中的值时,返回指向该对象的指针。因此,如果该值被修改,那么字典中的值也会被更改。
在Matlab:
clear all; close all; clc;
some_dict_with_struct=containers.Map;
some_dict_with_struct('a')=struct;
item = some_dict_with_struct('a');
item.attribute = 1;
disp(item.attribute); % displays "1"
disp(some_dict_with_struct('a')); % has no fields?
在Python中
class A:
def __init__(self,a):
self.a=a
return
A(4)
some_dict_with_struct={}
item = A(4)
some_dict_with_struct['a'] = item
print(some_dict_with_struct['a'].a) # returns "4"
item.a = 0
some_dict_with_struct['a']
print(some_dict_with_struct['a'].a) # returns "0"
有人能帮我确定一个可比较的数据结构在MatLab中使用,将实现类似的行为,Python?你能确认一下我对这种行为的看法是正确的吗?
谢谢。
问题不在于containers.Map
,而在于它所包含的项目。可以在句柄类中捕获所需的行为,而不是使用struct
。
在一个名为Item.m
的单独文件中:
%%
classdef Item < handle
properties
attribute = 0;
end
end
观察这个行为:
some_dict_with_struct=containers.Map;
some_dict_with_struct('a') = Item;
item = some_dict_with_struct('a');
item.attribute = 1;
disp(item.attribute); % displays "1"
disp(some_dict_with_struct('a')); % displays "1"