bloggerads

2017年8月4日 星期五

Python : class method / static method / method

This is a good example for showing the difference between class method, static method and method in Python.


class Demo:     
    y=1 # class (or static) variable
    def __init__(self,z):
        self.z = z

    @classmethod
    def class_method(cls, x):
        return x + cls.y

    @staticmethod
    def static_method(x):
        return x  #cannot invoke cls.z

    def method(self, x):
        return x + self.z


print Demo.class_method(2)  # show 3
print Demo.static_method(2)  # show 2

#print Demo.method(2) #Error, must declare first
demo = Demo(2)
print demo.method(2) # show 4

沒有留言:

張貼留言