我是 Python 新手。我想在 python 中使用类似 MATLAB 的结构。我已经在 stackoverflow 中看到了几个使用字典的解决方案,例如 this和 this .但是,我觉得下面代码中的虚拟对象方法更像 MATLAB,使用起来更自然,因为我们不需要为属性名称加上双引号。我的用例是以一种随意的方式单独将几个对象包装在一起,这样一些函数就不需要有一长串参数。例如,下面的最后一个函数只有两个参数,而不是 6 个。
我的问题是:现在我必须在我的脚本中定义虚拟类结构。有必要吗?如果我的许多脚本需要使用它,我将不得不把它放在我的所有函数都可以访问的地方。是否已经存在我可以使用的内置“虚拟类”?
import numpy as np
class Structure:
pass
def construct_network():
net = Structure()
net.n = 100;
net.Weights = np.random.rand(net.n, net.n)
net.biases = np.random.rand(net.n, 1)
return net
def a_function_operate_on_two_nets(net1, net2):
# Use the net1 and net2 here.
最佳答案
添加python3.3 types.SimpleNamespace
这就是你要找的。对于早期版本的 python,您可能不得不依赖为类似(足够接近)任务构建的东西——例如argparse.Namespace
.
当然,collections.namedtuple
如果您确实想要一些结构化(通常比非结构化的东西更受欢迎),那么总是有collections.namedtuple
。
关于python - Python 中类似 MATLAB 的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25964467/