/    /  Python Instance Objects

Python Instance Objects

In this tutorial, we will learn python in detail.

 

Python is an Object-oriented programming language. OOP’s allows variables to be used at the class level or the instance level.

Variables at the class level are called class variables and variables at the instance level are called instance variables.

 

Class variables:

 

These variables are defined within the class construction. Class variables are shared by all the instances of the class. Class variables are defined typically right below the class header and before the constructor method and other methods.

 

Example for class variable:

 

class Shark:
    animal_type = "fish"

 

For the above example we can create the instance of the Shark class and print the variable by using dot notation.

 

Example:

 

class Shark:
    animal_type = "fish"

new_shark = Shark()
print(new_shark.animal_type)

 

Output:

 

fish

 

Instance variables:

 

Instances of the class own instance variables. Instance variables are defined within methods.

 

Example:

 

class Shark:
   def __init__(self, name, age):
       self.name = name
       self.age = age
new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)

 

Output:

 

­­­­­­­­

Sammy
5

 

In the above example name and age are instance variables. Shark object is created and we defined these variables which are passed as parameters within the constructor method.

 

Working with Class and Instance Variables Together

 

We can utilize class variables and instance variables at the same time.

 

Example:

 

class Shark:

   # Class variables
   animal_type = "fish"
    location = "ocean"

   # Constructor method with instance variables name and age
   def __init__(self, name, age):
       self.name = name
        self.age = age

   # Method with instance variable followers
   def set_followers(self, followers):
        print("This user has " + str(followers) + " followers")

def main():
   # First object, set up instance variables of constructor method
    sammy = Shark("Sammy", 5)

   # Print out instance variable name
   print(sammy.name)

   # Print out class variable location
   print(sammy.location)

   # Second object
    stevie = Shark("Stevie", 8)

   # Print out instance variable name
    print(stevie.name)

   # Use set_followers method and pass followers instance variable
    stevie.set_followers(90)

   # Print out class variable animal_type
    print(stevie.animal_type)

if __name__ == "__main__":
    main()

 

Output:

 

Sammy
ocean
Stevie
This user has 90 followers
fish