简体   繁体   中英

Python - How can I get a list of all the fields in my struct?

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 !!!

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()

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())

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)

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'>}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM