An Instance in a instant

·

2 min read

Python has an object that is created by a class called an instance.

First, a class is a manual that tells an instance how to behave and define attributes. Inside the class, instance states and behaviors are defined. They have unique attributes and methods that they can access in their class. Below I have class and instance:

class Member:
    pass

# A instance
m1 = Member()

Creating an Instance:

class Member:
# instance method
    def __init__( self, member_id, name, gender, age )
        self.member_id: member_id
        self.name = name
        self.gender = gender
        self.age = age

# A instance
m1 = Member( 178962, "Nicole", "F", 24 )

An instance is created with the class name and parentheses. Inside the parentheses are arguments that get passed to an instance method: __init__( ). When m1 calls Member( ) it past 4 arguments: the member ID, name, gender, and age. Here is what Python does with those arguments:

  1. Calls the __new__() method to create a new empty instance of the Member class

  2. Calls the __init__() method and passes the name argument

  3. Initializes the self.name attribute with the name value

  4. Returns the new instance

The instances are initialized by the __init__( ) method. Inside of the __init__( ) method we can also set a default value.

class Member:
# instance method
    def __init__( self, member_id, name, gender="undefined", age="undefined" )
        self.member_id: member_id
        self.name = name
        self.gender = gender
        self.age = age

# A instance
m1 = Member( 178962, "Nicole", "F", 24 )

Heads up if you try to put the defaulted arguments before the non-defaulted arguments it will break the code. So make sure to add the defaulted arguments last.

Conclusion

To sum it all up call the class followed by parentheses with your arguments to pass to __init__( ). The __init__() method initializes the instance attributes.