shaoyl85
shaoyl85

Reputation: 1964

MATLAB like structure in Python

I'm new to Python. I would like to use MATLAB-like structure in python. I already see several solutions in stackoverflow using dictionary, such as this and this. However, I feel like the dummy object approach in the code below is more MATLAB-like and more natural to use since we don't need the double quotes for names of attributes. The use case for me is sololy to wrap several objects together in a casual way, such that some of the functions don't need to have a long list of arguments. For example, the last function below only has two arguments rather than 6.

My question is: now I have to define the dummy class Structure in my script. Is it necessary? If many of my scripts need to use it, I will have to put it somewhere that all my functions can access. Is there a built-in "dummy class" already existed I can just use?

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.

Upvotes: 1

Views: 630

Answers (2)

Nontraxx
Nontraxx

Reputation: 9

You created this structure in a file. For example put that code in struct.py then in another python script just write from struct.py import Structure or if you created other structures you can import all that clases using from struct.py import *

Upvotes: 1

mgilson
mgilson

Reputation: 310099

python3.3 added types.SimpleNamespace which is what you're looking for. For earlier versions of python, you may have to rely on something built for a similar (close enough) task -- e.g. argparse.Namespace.

And, of course there is always collections.namedtuple if you actually want something structured (which is usually preferred to something unstructured).

Upvotes: 3

Related Questions