| | |
Why use a Python class?
Thread Solved |
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!
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
Here is one example that explains a little about self and class instance and method:
python Syntax (Toggle Plain Text)
# a typical Python class example # newer class convention uses inheritance place holder (object) class Account(object): # __init__() initializes a newly created class instance, # 'self' refers to the particular class instance # and also carries the data between the methods. # You have to supply the initial account balance # during creation of the class instance. def __init__(self, initial): self.balance = initial def deposit(self, amt): # a function within a class is called a method # self always starts the argument list of a method self.balance = self.balance + amt def withdraw(self,amt): self.balance = self.balance - amt def getbalance(self): return self.balance # create two new class instance, Mary's and Tom's account mary = Account(1000.00) # start with initial balance of 1000.00 tom = Account(3000.00) # tom is lucky he starts with 3000.00 # Mary makes deposits and a withdrawel mary.deposit(500.00) mary.deposit(23.45) mary.withdraw(78.20) # Tom also accesses his account tom.withdraw(1295.50) # now look a the account balances print "Mary's balance = $%0.2f" % mary.getbalance() # $1445.25 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!
This sample code should shed some light on class inheritance ...
python Syntax (Toggle Plain Text)
# class Teacher and class Student inherit from class SchoolMember # the base or super class class SchoolMember(object): '''represents any school member''' def __init__(self, name, age): self.name = name self.age = age def detail(self): '''show name and age, stay on same line (trailing comma)''' print 'Name: %-13s Age:%s' % (self.name, self.age), # use the base class as argument to inherit from class Teacher(SchoolMember): '''represents a teacher''' def __init__(self, name, age, subject): # call the base class constructor ... # it assigns name, age to self.name, self.age SchoolMember.__init__(self, name, age) self.subject = subject def detail(self): '''teaches this course''' SchoolMember.detail(self) print 'Teaches course: %s' % self.subject class Student(SchoolMember): '''represents a student''' def __init__(self, name, age, grades): SchoolMember.__init__(self, name, age) self.grades = grades def detail(self): '''student grades''' SchoolMember.detail(self) print 'Average grades: %d' % self.grades # teacher has name age and subject taught t1 = Teacher('Mr. Schard', 40, 'Beginning Python 101') # student has name, age and average grade (max 100) s1 = Student('Abigale Agat', 20, 92) s2 = Student('Bertha Belch', 22, 65) s3 = Student('Karl Kuss', 21, 98) s4 = Student('Tom Tippit', 22, 77) s5 = Student('Zoe Zeller', 20, 88) print '-'*55 # list of instances, Teacher t1 and Students s1 ... s5 members = [t1, s1, s2, s3, s4, s5] sumgrades = 0 for member in members: memberType = member.detail() try: sumgrades += member.grades except AttributeError: pass # this would be a teacher, has no grades so skip print "\n%s's students class-average grades = %d" % (t1.name, sumgrades/5) """ output --> Name: Mr. Schard Age:40 Teaches course: Beginning Python 101 Name: Abigale Agat Age:20 Average grades: 92 Name: Bertha Belch Age:22 Average grades: 65 Name: Karl Kuss Age:21 Average grades: 98 Name: Tom Tippit Age:22 Average grades: 77 Name: Zoe Zeller Age:20 Average grades: 88 Mr. Schard's students class-average grades = 84 """
May 'the Google' be with you!
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
(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
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
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.
I'm thinking this stuff could help me out alot with a program I'm making now.
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
http://www.python.org/doc/current/tut/node11.html
May 'the Google' be with you!
![]() |
Similar Threads
- Starting Python (Python)
- Python - Importing Data with a Class (Python)
- a class question (Python)
Other Threads in the Python Forum
- Previous Thread: Number to Word Converter (Python)
- Next Thread: Python GUI build: Logic Complications and Mistakes
| Thread Tools | Search this Thread |
abrupt ansi anti approximation assignment avogadro backend beginner binary bluetooth calculator character cmd code customdialog cx-freeze data decimals dictionaries dictionary directory dynamic error examples exe file float format function gnu graphics gui heads homework http ideas import input itunes java launcher leftmouse line linux list lists loop module mouse number numbers output parsing path pointer port prime programming progressbar projects push py2exe pygame pyglet pyqt python random recursion schedule screensaverloopinactive script scrolledtext sqlite ssh statistics string strings sudokusolver sum table terminal text thread threading time tlapse tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable ventrilo wikipedia write wxpython xlib






