Demonstrating the class, static and instance methods



Demonstration of class , static and instance methods


Class method is created with a decorator @classmethods and are the methods belongs to the class, not to the objects.

  1. The first argument is the class (cls) itself
  2. Called using an object of the class
  3. Called using the class name itself
Can be used to change the state of the class, as in example below we have an enrolment variable which decides if the enrolments are open or not!



Static method is created with a decorator @staticmethod, doesn't deal with the state of the class, used for static purposes, like we have used in the below.

  1. Called with the object of the class
  2. Called with the class itself
  3. There is no as such first argument self like instance methods and cls like the class methods.

Instance Method  are the instance and hold the state of the object and each object has its own copy of the variable associated with it.

  1. The first argument is the self, the object
  2. each object has its own copy


import pdb
from pprint import pprint
from collections import namedtuple as nt

Player = nt("Player", ["Name", "Age", "Sport"])


class Students:
enrolment = True
@staticmethod
def decider(age, sport):
if age < 18 and sport == "swimming":
return False
return True

@classmethod
def start_enrolment(cls):
Students.enrolment = True

@classmethod
def stop_enrolment(cls):
Students.enrolment = False

def __init__(self):
self.students = []

def enrol_student(self, name, age, sport):
if not Students.enrolment:
print("Sorry Enrolments are not open, try again later")
return
if not self.decider(age, sport):
print(f"Enrolment not possible in age {age} for {sport}")
return

self.students.append(Player(name, age, sport))

@property
def get_students(self):
return self.students

if __name__ == "__main__":
pdb.set_trace()
print(f"Enrol Students")





-> print(f"Enrol Students")
Create an instance of the class
(Pdb) obj = Students()

Static Method - Tried to enrol a student for swimming
(Pdb) obj.enrol_student("Sachin", 15, "swimming")
Enrolment not possible in age 15 for swimming

Instance Method - Enrol the student for cricket
(Pdb) obj.enrol_student("Sachin", 15, "cricket")


Instance Method - Getting the enrolled students
(Pdb) pprint(obj.get_students)
[Player(Name='Sachin', Age=15, Sport='cricket')]

Class Method - Stop Enrolment 
(Pdb) obj.stop_enrolment()

Instance Method - Enrol the student for cricket
(Pdb) obj.enrol_student("Virat", 15, "cricket")
Sorry Enrolment is not open, try again later
 
Class Method - Class used to call the start Enrolment 
Pdb) Students.start_enrolment()

Instance Method - Enrol the student for cricket
(Pdb) obj.enrol_student("Hardik", 21, "cricket")

Instance Method - Getting the enroled students
(Pdb) pprint(obj.get_students)
[Player(Name='Sachin', Age=15, Sport='cricket'),
 Player(Name='Hardik', Age=21, Sport='cricket')]

Comments

Popular Posts