Why use a Python class?

Thread Solved

Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Why use a Python class?

 
0
  #1
Oct 24th, 2006
In the last couple of threads people have used the Python class, but really don't seem to know how to use them properly, or why to use them. Hence my question: "Why would you use a class in Python?"

I though only Java forces you to use OOP.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,523
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Why use a Python class?

 
0
  #2
Oct 24th, 2006
A few reasons to use Python classes come to mind, one is to group functions (in a class they are called methods) that belong together. This is sort of what modules do. However, classes have a leg up on modules, they have a way to inherit other classes and establish a tree search structure for attributes in any of these inherited/linked classes. You can go witout classes and OOP, but the ease of reuse of existing code makes a difference as you write larger programs.

So keep OOP in mind, introduce/immerse yourself gradually in this somewhat different world. Do it only if you are familiar with Python programming as a whole. There are some complex issues to tackle and a real beginner simply gets lost!
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Why use a Python class?

 
0
  #3
Nov 6th, 2006
Looks like I have to find myself some good Python class examples. Are there any around?
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,972
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 920
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Why use a Python class?

 
0
  #4
Nov 7th, 2006
Here is one example that explains a little about self and class instance and method:
  1. # a typical Python class example
  2. # newer class convention uses inheritance place holder (object)
  3.  
  4. class Account(object):
  5. # __init__() initializes a newly created class instance,
  6. # 'self' refers to the particular class instance
  7. # and also carries the data between the methods.
  8. # You have to supply the initial account balance
  9. # during creation of the class instance.
  10. def __init__(self, initial):
  11. self.balance = initial
  12.  
  13. def deposit(self, amt):
  14. # a function within a class is called a method
  15. # self always starts the argument list of a method
  16. self.balance = self.balance + amt
  17.  
  18. def withdraw(self,amt):
  19. self.balance = self.balance - amt
  20.  
  21. def getbalance(self):
  22. return self.balance
  23.  
  24.  
  25. # create two new class instance, Mary's and Tom's account
  26. mary = Account(1000.00) # start with initial balance of 1000.00
  27. tom = Account(3000.00) # tom is lucky he starts with 3000.00
  28.  
  29. # Mary makes deposits and a withdrawel
  30. mary.deposit(500.00)
  31. mary.deposit(23.45)
  32. mary.withdraw(78.20)
  33.  
  34. # Tom also accesses his account
  35. tom.withdraw(1295.50)
  36.  
  37. # now look a the account balances
  38. print "Mary's balance = $%0.2f" % mary.getbalance() # $1445.25
  39. print "Tom's balance = $%0.2f" % tom.getbalance() # $1704.50
Last edited by vegaseat; Nov 7th, 2006 at 12:16 pm. Reason: additional comments
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,972
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 920
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Why use a Python class?

 
0
  #5
Nov 8th, 2006
This sample code should shed some light on class inheritance ...
  1. # class Teacher and class Student inherit from class SchoolMember
  2.  
  3. # the base or super class
  4. class SchoolMember(object):
  5. '''represents any school member'''
  6. def __init__(self, name, age):
  7. self.name = name
  8. self.age = age
  9.  
  10. def detail(self):
  11. '''show name and age, stay on same line (trailing comma)'''
  12. print 'Name: %-13s Age:%s' % (self.name, self.age),
  13.  
  14. # use the base class as argument to inherit from
  15. class Teacher(SchoolMember):
  16. '''represents a teacher'''
  17. def __init__(self, name, age, subject):
  18. # call the base class constructor ...
  19. # it assigns name, age to self.name, self.age
  20. SchoolMember.__init__(self, name, age)
  21. self.subject = subject
  22.  
  23. def detail(self):
  24. '''teaches this course'''
  25. SchoolMember.detail(self)
  26. print 'Teaches course: %s' % self.subject
  27.  
  28. class Student(SchoolMember):
  29. '''represents a student'''
  30. def __init__(self, name, age, grades):
  31. SchoolMember.__init__(self, name, age)
  32. self.grades = grades
  33.  
  34. def detail(self):
  35. '''student grades'''
  36. SchoolMember.detail(self)
  37. print 'Average grades: %d' % self.grades
  38.  
  39. # teacher has name age and subject taught
  40. t1 = Teacher('Mr. Schard', 40, 'Beginning Python 101')
  41. # student has name, age and average grade (max 100)
  42. s1 = Student('Abigale Agat', 20, 92)
  43. s2 = Student('Bertha Belch', 22, 65)
  44. s3 = Student('Karl Kuss', 21, 98)
  45. s4 = Student('Tom Tippit', 22, 77)
  46. s5 = Student('Zoe Zeller', 20, 88)
  47.  
  48. print '-'*55
  49.  
  50. # list of instances, Teacher t1 and Students s1 ... s5
  51. members = [t1, s1, s2, s3, s4, s5]
  52. sumgrades = 0
  53. for member in members:
  54. memberType = member.detail()
  55. try:
  56. sumgrades += member.grades
  57. except AttributeError:
  58. pass # this would be a teacher, has no grades so skip
  59.  
  60. print "\n%s's students class-average grades = %d" % (t1.name, sumgrades/5)
  61.  
  62. """
  63. output -->
  64. Name: Mr. Schard Age:40 Teaches course: Beginning Python 101
  65. Name: Abigale Agat Age:20 Average grades: 92
  66. Name: Bertha Belch Age:22 Average grades: 65
  67. Name: Karl Kuss Age:21 Average grades: 98
  68. Name: Tom Tippit Age:22 Average grades: 77
  69. Name: Zoe Zeller Age:20 Average grades: 88
  70.  
  71. Mr. Schard's students class-average grades = 84
  72. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Why use a Python class?

 
0
  #6
Nov 10th, 2006
Thanks a lot for the class examples, now using a class makes a little more sense. I guess you really have to think ahead where a class would come in handy!

Are there any guidelines when to use and not to use a class?
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Why use a Python class?

 
0
  #7
Nov 11th, 2006
Originally Posted by sneekula View Post
Are there any guidelines when to use and not to use a class?
(1) Well, one of the most important prerequisites for having clean code is to use the right data structure. A class can help you construct the data structure that you need instead of having to force something awkward to work.

For example, if I were writing software to model ray tracing or some other physics-heavy application, I would define a vector class so that my math operations could be as natural-looking as possible:

[php]
a = Vector(1,2)
b = Vector(3,4)
c = a + b # does vector addition -- requires writing an __add__ method
[/php]

as opposed to

[php]
a = [1,2]
b = [3,4]

c = []
for i in range(len(a)):
c.append(a[i] + b[i])
[/php]

Basically, classes allow you to write objects whose code mimicks the way you think.

(2) If you create a class with well-written methods, you can import that class everywhere without having to worry about the code breaking. This becomes really important when you get to big projects.

(3) Objects are the most natural way to represent GUI items. If you use Tkinter or some other GUI, you will end up needing to use objects and probably needing to create your own.

Writing with classes was intimidating to me for about a month, but after I wrote a couple of projects, it became very natural.

Have fun!

Jeff
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 187
Reputation: Matt Tacular is an unknown quantity at this point 
Solved Threads: 7
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Unverified User

Re: Why use a Python class?

 
0
  #8
Nov 29th, 2006
I too am a beginer to python and have codded a few programs. I always knew of classes but never knew anything about them. I still have yet to use a class in any of my code, and I was wondering if anyone could post a link to some tutorials or something that is designed for the beginner.

I'm thinking this stuff could help me out alot with a program I'm making now.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,972
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 920
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Why use a Python class?

 
0
  #9
Dec 8th, 2006
For some nice details on classes, you might want to look at the official Python tutorial at:
http://www.python.org/doc/current/tut/node11.html
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC