Variables, Methods And Inner Class In Python

In my previous article classes and objects, we learned about basics of classes, objects, constructor, and how all these are interrelated and implemented.

In this article we will touch base with further concepts:

  • Types of Variables
  • Types of Methods
  • Inner Class

Types of Variables in Python

There are 2 types of variables when it comes to OOPS concept in Python:

  • Instance Variables: Inside __init__
  • Class/Static Variables: Outside __init__

1. Instance Variables

  • These types of variables are different for every different object and if it is changed at any point in time, it will not effect other objects.
  • Declared inside __init__

Example

class dog:

  def __init__(self):
    self.age=5        #instance variable
    self.breed='pug'  #instance variable

d1= dog()
print(d1.age,d1.breed)
d2= dog()
d2.age=7     #changing value of Instance Variable
print(d2.age,d2.breed)

Output- 

In the above example, we saw how we declare an instance variable and if its value is changed at any point then it will not reflect on any other object, it will only change the value of a particular object it is used with.

2. Class Variables

  • These types of variables are common for whole class, so every method or inner class can access these.
  • If this variable is changed, then it effects all other objects.
  • Declared outside __init__

Example

class dog:

  legs=4  #Class/Static Variable

  def __init__(self):
    pass

d1= dog()
print(d1.legs)
dog.legs=5 #changing value of Class Variable
d2= dog()
print(d2.legs)

Output- 

In the above example, we saw how we declare a class variable and if its value is changed at any point then it will reflect in the whole program and the values of the other objects will also be changed.

Types of Method in Python

There are 3 types of Methods when it comes to OOPS concept in Python:

1. Instance Method

Instance methods are of 2 types:

  • Accessor Methods - These are used to fetch the values. Also known as Getter.
  • Mutator Methods - These are used to update the values. Also known as Setter.

Example

class student_marks:

 
  def __init__(self,s1,s2,s3):
    self.s1=s1  #instance variable
    self.s2=s2  #instance variable
    self.s3=s3  #instance variable

  def total_marks(self):           #instance method
    return self.s1 + self.s2 + self.s3

  def get_student_s1(self):        #GETTER
    return self.s1

  def set_student_s1(self,value):  #SETTER
    self.s1=value

obj1= student_marks(98,99,87)
obj2= student_marks(87,85,92)
print("Total Marks of student1 are:",obj1.total_marks())
print("Total Marks of student1 are:",obj2.total_marks())

Output- 

2. Class Method

  • In class method, we use ‘cls’ instead of ‘self’ because we want the reference to the class.

So how do we convert a simple function/method into a class method?

Answer is, by using decorators.

  • When we use @classmethod before a method, it converts it into a class method which means that this method now needs to be converted into a class method.
  • @classmethod is a decorator here. Class methods are bound to a class rather than an object but thy can be called by both class and object.

Example

class schoolClass:

  school_name= "SMJPS"      #class variable

  @classmethod              #class decorator
  def info(cls):            #class method
    print(cls.school_name)

print(schoolClass.info())

Output

As you can see in the above example, we haven’t created any object of class schoolClass but still, we are able to access class variable school_name , this is because now info is a class method and will give reference to schoolClass using ‘cls’ as instance.

3. Static Method

  • Suppose you don’t want any reference, meaning: you don’t want either object or class reference, in these cases we use Static Methods.
  • In these types of methods, no parameter is required.
  • To make a method static, we use decorator- @staticmethod

Example

class schoolClass:

  school_name="SMJPS" #class attribute

  def __init__(self):
    self.age = 20     #instance attribute

  @staticmethod       #static decorator
  def info():         #static method
    print("This is static method")

print(schoolClass.info())
obj=schoolClass()
obj.info()

Output

But static method cannot access the class attributes or the instance attributes.

class schoolClass:

  school_name="SMJPS" #class attribute

  def __init__(self):
    self.age = 20     #instance attribute

  @staticmethod       #static decorator
  def info():         #static method
    print("This is static method")

print(school_name,self.age)

Output

Inner Class in Python

As the name suggests, a class within a class is called Inner Class.

When do we use it?

Let’s say, I have a class course

So, in this class we can pass 3 values easily inside __init__ , i.e. course_id, couse_name, course_duration. But what about course_type? This particular value has sub values. So, cases like these are handled by inner class concept. Now within a class course, we will create an inner class- class course_type

Let’s see, how it’s done!

class course:               #outer class

  def __init__(self,course_id, course_name, course_duration):
    self.course_id = course_id
    self.course_name = course_name
    self.course_duration = course_duration
    self.type = self.course_type()  #object of inner class

  def show(self):        
    print(self.course_id,self.course_name,self.course_duration)

  class course_type:  #inner class

    def __init__(self):     # __init__ of inner class
      self.core='core'
      self.elective='elective'
      self.ancillary='ancillary'

c1=course(2000,'Maths',3)
c1.show()
print(c1.type.core)  #accessing variables of inner class

Output

In the above program, we learned how to create object of inner class inside outer class.

You can also create an object of inner class outside the outer class, provided you use outer class name to call it, meaning:

class course:               #outer class

  def __init__(self,course_id, course_name, course_duration):
    self.course_id = course_id
    self.course_name = course_name
    self.course_duration = course_duration

  def show(self):        
    print(self.course_id,self.course_name,self.course_duration)

  class course_type:  #inner class

    def __init__(self):     # __init__ of inner class
      self.core='core'
      self.elective='elective'
      self.ancillary='ancillary'
     
c1=course(2000,'Maths',3)
c1.show()
t1=course.course_type()  #object of inner class outside outer class
print(t1.elective)

Output-