What is the difference bw general method(self) and class method(@classmethod) in python class?

i would be glad if u explain by code.

1 Like

image

is it python? @ahana2018

A general method is specific to an instance of the class. And a class method (defined using the @classmethod decorator) is applicable to the whole class. Properties which are applicable to all the instances of a class are usually defined here and those which are specific to an instance of the class, go into the general methods. Example:

class Car:
    def __init__(self, color):
            self.color = color

    def get_color(self):
            return self.color

    @classmethod
    def red_cars(cls):
        # cls is the Car class
        print(cls)

Now, calling the functions using:

a = Car('Red')
a.get_color()
a.red_cars()

prints:

'Red'
<class '__main__.Car'>
None

None is printed out because the red_cars() method returned nothing.

1 Like

Mm Yes
Welcome to CodeChef Disscuss!!!