Python - Class Class Creation

Introduction

The following code shows how to create Person class.

Python begins module names with a lowercase letter and class names with an uppercase letter.

# File person.py (start) 
class Person:            # Start a class 

Constructors

The following code adds constructor to the Person class.

We use self in the __init__ constructor method.

__init__ contains code run automatically by Python each time an instance is created.

# Add record field initialization 
class Person: 
   def __init__(self, name, job, pay):      # Constructor takes three arguments 
       self.name = name                     # Fill out fields when created 
       self.job  = job                      # self is the new instance object 
       self.pay  = pay 

Here, we pass in the data to be attached to an instance as arguments to the constructor method.

We assign them to self to retain them permanently.

self is the newly created instance object, and name, job, and pay become state information.

The job argument is a local variable in the scope of the __init__ function, but self.job is an attribute of the instance.

By assigning the job local to the self.job attribute, we save the passed-in job on the instance.

To make the argument optional.

# Add defaults for constructor arguments 

class Person: 
    def __init__(self, name, job=None, pay=0):         # Normal function args 
        self.name = name 
        self.job  = job 
        self.pay  = pay 

# Add incremental self-test code 
bob = Person('Bob Smith')                         # Test the class 
sue = Person('Sue Jones', job='dev', pay=100000)  # Runs __init__ automatically 
print(bob.name, bob.pay)                          # Fetch attached attributes 
print(sue.name, sue.pay)                          # sue's and bob's attrs differ 

bob object accepts the defaults for job and pay.

sue has values explicitly.

Related Topics