Tamir Einy
Tamir Einy

Reputation: 186

matlab like struct in python

Can you suggest clean way to represent this struct in python?

students = struct;
students(1).fname = 'john';
students(1).lname ='smith';
students(1).height = 180;

students(2).fname = 'dave';
students(2).lname = 'clinton';
students(2).height = 184;

Thanks!

Upvotes: 1

Views: 3532

Answers (3)

Jinglesting
Jinglesting

Reputation: 517

In Python, you can make a class (which is a bit like a struct but with more functionality) as follows:

class Student()
    def __init__(self, fname, lname, height):
        self.fname = fname
        self.lname = lname
        self.height = height

The __init__ function describes the information required to make a new student record. The 'self' argument just tells Python that you want to set these variables on an instance (an actual student record) rather than on the class (Which is a blueprint for student records). You can then create an instance of a Student as follows:

my_student = Student('Space', 'Man', 180)

You could make many of these instances and append each to a list:

all_students = [] # An empty list
all_students.append(my_student) # using the instance we've already created
all_students.append(Student('Jingle', 'Sting', 180)) # a new instance

You can then access the items in the list as follows:

all_students[1]

By creating a class, you can also create methods which apply to all instances of Students.

class Student()
    def __init__(self, fname, lname, height):
        self.fname = fname
        self.lname = lname
        self.height = height

    def get_height_in_meters(self):
        return self.height / 100

And use them like this:

my_student.get_height_in_meters()

You could even string accessing student records from the list directly with methods that apply to them like so:

all_students[1].get_height_in_meters()

Upvotes: 2

Saim Raza
Saim Raza

Reputation: 1470

Use a list of namedtuple(s):

import collections
harry = student(fname="harry", lname="Potter", height=160)
hermione = student(fname="hermione", lname="Granger", height=140)

students = [
    harry,
    hermione
]
print(students[0].fname)
print(students[1].fname)

Upvotes: 1

sshashank124
sshashank124

Reputation: 32207

This can accomplished by creating a list of dictionaries as follows:

students = [
    {'fname': 'john', 'lname': 'smith', 'height': 180},
    {'fname': 'dave', 'lname': 'clinton', 'height': 184}
]

Then, you can get the n-th student by doing students[n] or a specific field from the n-th student by doing students[n]['fname']

Upvotes: 1

Related Questions