Python - Class Class Methods


The following code adds methods to the Person class.

class Person: 
    def __init__(self, name, job=None, pay=0): = name 
        self.job  = job  = pay 
    def lastName(self):                               # Behavior methods 
        return[-1]                  # self is implied subject 
    def giveRaise(self, percent): = int( * (1 + percent))      # Must change here only 

if __name__ == '__main__': 
    bob = Person('Bob Smith') 
    sue = Person('Sue Jones', job='dev', pay=100000) 
    print(bob.lastName(), sue.lastName())             # Use the new methods 
    sue.giveRaise(.10)                                # instead of hardcoding 

Class methods are normal functions that are attached to classes and process instances of those classes.

The instance is the subject of the method call and is passed to the method's self argument automatically.

Python tells a method which instance to process by automatically passing it in to the first argument, usually called self.

Related Topics