Table of Contents

    Creating and Using Objects in Python: A Step-by-Step Guide

    Creating Objects

    • An object is created by calling the class name followed by a pair of parenthesis.
    
    class Person:             
        pass                    
    p1 = Person()      # Creating the object 'p1'
    print(p1)            # -> '<__main__.Person object at 0x0A...>'
    
    • The output of print on object p1, tell you what class it belongs to and hints on memory address it is referenced to.

    Setting Attributes

    • You can set attributes, one a time, to an instantiated object and access it using the dot notation.

    • The value which is set to an attribute can be anything: a Python primitive, a built-in data type, another object. It can even be a function or a class.

    Example

    
    class Person:
        pass
    p1 = Person()
    p1.fname = 'Jack'
    p1.lname = 'Simmons'
    print(p1.fname, '-', p1.lname)  # -> 'Jack - Simmons'
    

    Setting Attributes Contd..

    • You can also set multiple attributes, at once, by defining the initializer method, __init__, inside the class.

    • This method is called by default, during an object creation.

    • It takes values passed inside the parenthesis, during an object creation, as it's arguments.

    • It also takes self as the first argument, which refers to the current object.

    Setting Attributes Example

    • In the following example, Person class sets two attributes using __init__ method.
    
    class Person:
        def __init__(self, fname, lname):
            self.fname = fname
            self.lname = lname
    p1 = Person('George', 'Smith')   
    print(p1.fname, '-', p1.lname)           # -> 'George - Smith'
    

    Documenting a Class

    Each class or a method definition can have an optional first line, known as docstring.

    Example

    
    class Person:
        'Represents a person.'
        def __init__(self, fname, lname):
            'Initialises two attributes of a person.'
            self.fname = fname
            self.lname = lname
    

    Understanding a Class

    Once documented, you can load the script into an interactive interpreter and run help command on Person class.

    
     
    >>>help(Person)
    
    Help on class Person in module __main__:
    
    
    
    class Person(builtins.object)
    
     |  Represents a person.
    
     |  
    
     |  Methods defined here:
    
     |  
    
     |  __init__(self, fname, lname)
    
     |      Initialises two attributes of a person.
    
     |  
    
    ... and more