Red Security

Full Version: Python 3.5: Class Methods
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: BFMMlbcQvml9HSqXcvNp]
Class Methods:
                 We already know about methods and we use a lot of methods inside the class for your reminder let’s have a look at the below example.

Code:
class Pet:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def show_info(self):
        print("Your pet name is " + self.name +" and age is "+ str(self.age))

dog = Pet("Jemsi", 8)
dog.show_info()


In this example there is only one method which is what we studied before that only works on objects of class. And now we will discuss the class methods which are the subject of this thread. The class methods are called by a decorator. We have already discussed the decorators in previous threads. These are bound to the class itself and not with instances of that class. It takes class as arguments. The first argument of class method is cls which refers to the class itself, But it will not generate error if you write it in any form but The cls is best practice in python .So let’s have a look at the example of it and try to understand how it works.



Look at this example we have created a class named Students and school name is a class variable and we then created a constructor that will be called whenever we instantiate the class.
And then @classmethod is a decorator which is compulsory to be called before making a class method and then we created a method which will take names as arguments and assign this to class variables. This way we can change the class state by changing its variables.

Code:
from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @classmethod
    def calculate_age(cls, name , birth_year):
        return(cls(name,date.today().year - birth_year))
    def show_info(self):
        print(self.name + " is " + str(self.age) + " Years old")


p1 = Person("Covid", 19)
p1.show_info()
p2 = Person.calculate_age("New Covid", 2012)
p2.show_info()


So in this example you can see that we have one constructor that takes a person's name and age as arguments and the show_info() method will show it to us.  But the class method is taking class ,name and birth_year as arguments and calculate the age and then makes an object and assigns to it but keep in mind that calculate is working on class directly as you can see we called it with class name as Person.calculate_age("New Covid", 2012) but we called show_info with object name that is the main difference between both methods. I hope you got the point.

When you change the class variable and its value will also be changed in each instance of class let’s have a look at this example

Code:
class Students:
    school_name = "Any Name"
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @classmethod
    def new_school(cls, name):
        cls.school_name = name

    def show_info(self):
        print(self.name ," is ", str(self.age)," years old and study in", Students.school_name)

s1 = Students("Covid", 32)
s1.show_info()
Students.new_school('New Name')
s1.show_info()

In this example school  name is firstly Any name but then we change it to New name so it changed and that’s it for today’s topic hope You got the whole idea behind this topic.


"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"