Sep defs not updating

class A(object): x = 0 def say_hi(self): pass @staticmethod def say_hi_static(): pass @classmethod def say_hi_class(cls): pass def run_self(self): self.x = 1 print self.x # outputs 1 self.say_hi() self.say_hi_static() self.say_hi_class() @staticmethod def run_static(): print A.x # outputs 0 # A.say_hi() # wrong A.say_hi_static() A.say_hi_class() @classmethod def run_class(cls): print cls.x # outputs 0 # cls.say_hi() # wrong cls.say_hi_static() cls.say_hi_class() 2- Static method cannot call self method but can call other static and classmethod 3- Static method belong to class and will not use object at all.4- Class method are not bound to an object but to a class.If your method accesses other variables/methods in your class then use @classmethod.

Another benefit of making the method a classmethod is so a subclass can decide to change it's implementation, maybe because it is pretty generic and can handle more than one type of cluster, so just checking the name of the class would not be [email protected] means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods).This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).Typically, it will access various attributes of the instance.For example, this is an instance of a string: take the instance as an argument. However, a module level function must live in the module and be specially imported to other places where it is used.A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. If a class method is called for a derived class, the derived class object is passed as the implied first argument.This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Class methods are different than C or Java static methods.It just gets the arguments that were passed, no implicit first argument.It is basically useless in Python -- you can just use a module function instead of a staticmethod.This can be useful when one wants the method to be a factory of the class as it gets the actual class (which called the method) as the first argument, one can instantiate the right class, even if subclasses are also concerned.A staticmethod is just a function defined inside a class.

768 comments

Leave a Reply

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

*