0

I've found the below code to allow me to create a "Matlab-like" struct variable:

class vidOutClass:
        pass

    vidOut = vidOutClass()
    vidOut.numOfFrames = numOfFrames
    vidOut.frameWidth = frameWidth
    vidOut.frameHeight = frameHeight

Now, I have my struct vidOut with 3 fields inside: "numOfFrames" , "frameWidth" , "frameHeight"

Is there a way for me to retrieve all existing fields in a struct?

In MATLAB it would like this:

fieldnames(vidOut)

which would yield a cell with all the field names.

THANKS !!!

4 Answers4

0

You can use .__dict__ to return a dictionary with the variable names as the keys and the values as the...values.

If you want to ONLY get the values, you can say .__dict__.values()

PythonPikachu8
  • 359
  • 2
  • 11
0

As I understand it, I don't think you're using Python classes correctly. You can achieve the equivalent of structs with a dictionary, whereas Python class is more intended to be used like an actual class, with instances and all.

vidOut = {}
vidOut["numOfFrames"] = numOfFrames
vidOut["frameWidth"] = frameWidth
vidOut["frameHeight"] = frameHeight

print(vidOut.keys())
Alex Ding
  • 148
  • 8
  • Thank you @Alexander Ding. I now understand that dictionary is best suited to resemble MATLAB's struct. My only dismay is that with dictionary I can't use the auto-fill feature. I mean, if I have a dictionary with 100 keys. I've created it last year, and I don't fully remember the exact names... now I'd like to find a key that related to "frames"... Can I type some like: 'vidOut.fr' and it show me all the keys that start with letters 'fr' ? Is there some workaround? – Mark Golberg Nov 03 '20 at 06:53
  • @MarkGolberg I think there are some efforts from Python to approximate C-like structs with more native support. See https://stackoverflow.com/a/45426493/7718577. – Alex Ding Nov 04 '20 at 14:26
0

The code you have provided might work but it is not the best practice, in Python you may use a class constructor function called __init__ as follows:

class VidOutClass:
    def __init__(self, num_of_frames, frame_width, frame_height):
        self.num_of_frames = num_of_frames
        self.frame_width = frame_width
        self.frame_height = frame_height

Then call it like this:

# Will create a VidOutClass object with 10 frames, and width x height of 150x150
vid_out = VidOutClass(num_of_Frames=10, frame_width=150, frame_height=150)

And then as stated here by @cnu you may use __dict__.keys(), or in your code:

for key, val in vid_out.__dict__.items():
    print(key, val)
OmerM25
  • 243
  • 2
  • 13
0

You can use dataclass.
Here is an example

from dataclasses import dataclass

@dataclass
class VidOutClass:
    numOfFrames: int = 0
    frameWidth: int = 5


vidOutClass = VidOutClass()
print(vidOutClass.__annotations__)

output - a dict where the key is the field name and the value is the field type

{'numOfFrames': <class 'int'>, 'frameWidth': <class 'int'>}
balderman
  • 22,927
  • 7
  • 34
  • 52