Python class method code snippets

Posted by

Hello Coders,

We have discussed the python class method on the Youtube channel. If you go through this, you will have a clear understanding of the class method, and also it will help to crack the interviews.

Here are the code snippets of the Videos Link here.

class Student:

    classteacher = "Mr.X"

    @classmethod
    def display(cls):
        print(f"hi... classteacher {Student.classteacher}")

    @classmethod
    def change_classteacher(cls,name):
        cls.classteacher = name
Student.display()
hi… classteacher Mr.X
Student.change_classteacher("Mr.Y")
Student.display()
hi… classteacher Mr.Y

Let’s see about this data format “Suresh-9-13”.

class Student:
    def __init__(self, name, std, roll):
        print("init called ......")
        self.name = name
        self.std = std
        self.roll = roll
   

    @classmethod
    def convert(cls,datastring):
        print("called method called .....")
        name, std, roll = datastring.split("-")
        data_x = cls(name, std, roll)
        return data_x
      
    def display_student_information(self):
        print(f"name {self.name}, std {self.std} roll {self.roll}")
student_1 = Student.convert("Sunita-22-60")
student_1.display_student_information()
called method called …..
init called ……
name Sunita, std 22 roll 60

Leave a Reply

Your email address will not be published. Required fields are marked *