User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 430,769 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,568 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums

Starting Python

Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,477
Reputation: vegaseat will become famous soon enough vegaseat will become famous soon enough 
Rep Power: 10
Solved Threads: 176
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #25  
Aug 11th, 2005
This shows you how to mimic a C struct type with an empty Python class ...
  1. # create a structure similar to C struct using an empty class
  2.  
  3. class Employee(object):
  4. pass
  5.  
  6.  
  7. john = Employee() # Create empty employee record/struct
  8. ted = Employee()
  9. mark = Employee()
  10.  
  11. # fill the fields of the record/struct
  12. john.name = 'John Johnson'
  13. john.dept = 'computer lab'
  14. john.salary = 3000
  15.  
  16. ted.name = 'Ted Tetris'
  17. ted.dept = 'human resources'
  18. ted.salary = 5000
  19.  
  20. mark.name = 'Mark Marksman'
  21. mark.dept = 'shipping area'
  22. mark.salary = 3200
  23.  
  24. # this works like a struct or record
  25. print "%s works in the %s and earns $%s/month" % (john.name, john.dept, john.salary)
  26.  
  27. print
  28.  
  29. # good for large employee lists, make a list of objects (not strings)
  30. empList = [john, ted, mark]
  31. for emp in empList:
  32. print "%s works in the %s and earns $%s/month" % \
  33. (getattr(emp, "name"), getattr(emp, "dept"), getattr(emp, "salary"))
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
Last edited by vegaseat : Mar 1st, 2007 at 3:14 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
All times are GMT -4. The time now is 5:06 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC