python - Python 中类似 MATLAB 的结构

标签 python matlab

我是 Python 新手。我想在 python 中使用类似 MATLAB 的结构。我已经在 stackoverflow 中看到了几个使用字典的解决方案,例如 thisthis .但是,我觉得下面代码中的虚拟对象方法更像 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/

相关文章:

python - pyusb:功能一次运行良好,第二次失败

python - 当 Python 对象的引用计数达到零时,注册清理的最可靠方法是什么?

matlab - 在 MATLAB 中,如何更改子图的背景颜色?

matlab - 第二个子图消失

python - 当由 C++ 线程程序调用的 Python 脚本本身调用时,OpenCV 函数会锁定

Python getter 、 setter

python - python列表理解中的冗余计算?

matlab - 3D 矩阵乘以 2D 矩阵

matlab - mat2gray对multithresh的影响

c++ - 导入函数 Matlab Coder 和 C++ 可执行文件