Python does not have a type like struct in C or record in Pascal, but it can be easily implemented with a class. This little code snippet shows you how to do it.
Class Implements a Structure/Record (Python)
# implement a structure similar to C struct or Pascal record using a class
# tested with Python24 vegaseat 11aug2005
class Employee(object):
def __init__(self, name=None, dept=None, salary=2000):
self.name = name
self.dept = dept
self.salary = salary
# one way to load the structure
john = Employee('John Johnson', 'software', 3000)
allan = Employee('Allan Armpit', 'hardware', 3400)
mark = Employee('Mark Marksman', 'shipping/handling', 2600)
zoe = Employee('Zoe Zoeller', 'wordprocessing', 2100)
# another way to load the structure
ted = Employee()
ted.name = 'Ted Tetris'
ted.dept = 'human resources'
ted.salary = 5000
# this works like a structure/record
print "%s works in %s and earns $%s/month" % (zoe.name, zoe.dept, zoe.salary)
print "%s works in %s and earns $%s/month" % (ted.name, ted.dept, ted.salary)
print '-'*60
# for a long list of employees you can do this
empList = [allan, john, mark, ted, zoe]
for emp in empList:
print "%s works in %s and earns $%s/month" % \
(emp.name, emp.dept, emp.salary)
print '-'*60
# ted had a sex change operation!
ted.name = "Tanya Tetris"
ted.salary = 4500
print "%s works in %s and earns $%s/month" % (ted.name, ted.dept, ted.salary)
print '-'*60
# use list comprehension to get the average salary
print "The average monthly salary of all employees: ",
average_salary = sum([emp.salary for emp in empList])/len(empList)
print "$%0.2f" % average_salary
niff 0 Newbie Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
niff 0 Newbie Poster
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
niff 0 Newbie Poster
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.