Difference between @classmethod and a method in python -


this question has answer here:

what difference between @classmethod , 'classic' method in python,

when should use @classmethod , when should use 'classic' method in python. classmethod must method referred class (i mean it's method handle class) ?

and know difference between @staticmethod , classic method thx

let's assume have class car represents car entity within system.

a classmethod method works class car not on 1 of of car's instances. first parameter function decorated @classmethod, called cls, therefore class itself. example:

class car(object):         colour = 'red'      @classmethod     def blue_cars(cls):         # cls car class         # return blue cars looping on cls instances 

a function acts on particular instance of class; first parameter called self instance itself:

def get_colour(self):     return self.colour 

to sum up:

  1. use classmethod implement methods work on whole class (and not on particular class instances):

    car.blue_cars() 
  2. use instance methods implement methods work on particular instance:

    my_car = car(colour='red') my_car.get_colour() # should return 'red' 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -