python中的静态函数与类函数区别与联系

静态方法和类方法在python2.2中被引用,经典类和新式类都可以使用。同时,一对内建函数:staticmethod和classmethod被引入,用来转化类中某一方法为这两种方法之一。

静态方法:

静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,主要是一些逻辑属于类,但是和类本身没有交互,即在静态方法中,不会涉及到类中的方法和属性的操作。可以理解为将静态方法存在此类的名称空间中。事实上,在python引入静态方法之前,通常是在全局名称空间中创建函数。

例子:

譬如,我想定义一个关于时间操作的类,其中有一个获得当前时间的函数。


import time class TimeTest(object): def __init__(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second @staticmethod def showTime(): return time.strftime("%H:%M:%S", time.localtime()) print(TimeTest.showTime()) t= TimeTest(2,10,10) nowTime= t.showTime() print(nowTime)

  

 如上,使用静态函数,既可以将获得时间的函数功能与实例解绑,我想获得当前时间的字符串时,并不一定需要实例化对象,此时更像是一种名称空间。

我们可以在类外面写一个简单的方法来做这些,但是这样做就扩散了类代码的关系到类定义的外面,这样写就会导致以后代码维护的困难。

静态函数可以通过类名以及实例两种方法调用

类方法:

类方法是将类本身作为对象进行操作的方法。他和静态方法的区别在于:不管这个方式是从实例调用还是从类调用,它都用第一个参数把类传递过来

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner/12179325#12179325

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod 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).

应用:

1、做一个颜色的动态匹配

class ColorTest(object):
    color = "color"

    @classmethod
    def value(self):
        return self.color

class Red(ColorTest):
    color = "red"

class Green(ColorTest):
    color = "green"

g = Green()
print(g.value())
print(Green.value())

  

 其中,基类做一个抽象共性,对于实际的颜色的值需要结合实际的类进行匹配。

2、假设我有一个学生类和一个班级类,想要实现的功能为:

班级类含有类方法:

执行班级人数增加的操作、获得班级的总人数

学生类继承自班级类,每实例化一个学生,班级人数都能增加。

最后,我想定义一些学生,然后获得班级中的总人数。

思考:这个问题用类方法做比较合适,因为我实例化的时学生,但是如果我从学生这一个实例中获得班级总人数是不合理的。

同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。

class ClassTest(object):
    __num = 0

    @classmethod
    def addNum(self):
        self.__num += 1

    @classmethod
    def getNum(self):
        return self.__num

    def __new__(self):
        ClassTest.addNum()
        return super(ClassTest, self).__new__(self)

class Student(ClassTest):
    def __init__(self):
        self.name = ''

a = Student()
b = Student()
print(ClassTest.getNum())

  

这里我用到魔术函数__new__,主要是为了在创建实例的时候调用人数累加的函数。

类函数可以通过类名以及实例两种方法调用!

注意:

python2 中,必须总要把一个方法声明为静态的,从而能够不带一个实例而调用它。

python3 中,如果方法只通过类调用,而不需要通过实例调用的话,不用非要声明为静态的。

class test:
    def show():
        print("show")

test.show()

  

原文链接:https://www.cnblogs.com/pinking/p/7944376.html 对原文的print稍有修改

原文地址:https://www.cnblogs.com/thomasbc/p/15060699.html