Instance method, Static method and Class method in Python

the most regular methods in python is instance method. something like this:

class Kls(object):
    def __init__(self, data):
        self.data = data

    def printd(self):
        print(self.data)

the printd method here is a instance method, because it takes “self” as its parameter, so that means this function/method will do things on current instance, like get its attributes.

class method:
before you define a class method, you have to use “@classmethod” decorator.
it’s like a method which can manipulate on class level instead of instance level.

class Kls(object):
    num_inst = 0

    def __init__(self):
        Kls.num_inst = Kls.num_inst + 1

    @classmethod
    def get_no_of_instance(cls):
        return cls.num_inst

the get_no_of_instance() is a class method, to count the number of instances of current class.

static method:
before you define a static method, you have to use “@staticmethod” decorator.
this method don’t need to take self.xxx as its parameter, instead, it can take any parameters it want. it’s just a regular method who takes parameter and return something, like string.charAt(index)

what is the difference between the static of Java and Python?
java分为静态和非静态成员,静态和非静态方法。所有的静态成员和静态方法都会随着类的定义而被分配和加载到内存中。而非静态只能在对象实例被创建的时候使用。所以静态数据对象可以说是 所有此类的实例共用 一旦被修改 全体都会被修改。
静态方法只能调用其他静态方法 但是非静态方法可以调用静态和非静态。
静态方法的调用 可以采取String.parseInt()或者instance.method name

posted @ 2020-10-18 00:11  EvanMeetTheWorld  阅读(27)  评论(0)    收藏  举报