Python - Class Class Creation


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 (start) 
class Person:            # Start a class 


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 = name                     # Fill out fields when created 
       self.job  = job                      # self is the new instance object  = 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 = name 
        self.job  = job  = 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(,                          # Fetch attached attributes 
print(,                          # sue's and bob's attrs differ 

bob object accepts the defaults for job and pay.

sue has values explicitly.

Related Topics