Python - User-Defined Classes


Consider the following code:

class Employee: 
         def __init__(self, name, pay):          # Initialize when created 
    = name                    # self is the new object 
     = pay 
         def lastName(self): 
             return[-1]        # Split string on blanks 
         def giveRaise(self, percent): 
    *= (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( )

Related Topic