Python - User-Defined Classes

Introduction

Consider the following code:

class Employee: 
         def __init__(self, name, pay):          # Initialize when created 
             self.name = name                    # self is the new object 
             self.pay  = pay 
         def lastName(self): 
             return self.name.split()[-1]        # Split string on blanks 
         def giveRaise(self, percent): 
             self.pay *= (1.0 + percent)         # Update pay in place 

Here, the class defines a new kind of object that will have name and pay attributes.

It has two bits of behavior coded as functions.

bob = Employee('Jack', 50000)             # Make two instances 
sue = Employee('Tom', 60000)             # Each has name and pay attrs 
print( bob.lastName() )                               # Call method: bob is self 
print( sue.lastName() )                               # sue is the self subject 
print( sue.giveRaise(.10) )                           # Updates sue's pay 
print( sue.pay )

Related Topic