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.

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!

Looks like I have to find myself some good Python class examples. Are there any around?

Here is one example that explains a little about self and class instance and method:

# 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

This sample code should shed some light on class inheritance ...

# 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
"""

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?

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:

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

as opposed to

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

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

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.

Hi,
Thanks a lot. This was very useful information. I am a beginner in python, I knew about classes but never used them. Instead i was using multiple function definitions. The above explaination made clear in which cases to use classes.

This question has already been answered. Start a new discussion instead.