python学习笔记-实例方法、类方法、静态方法

来源:互联网 发布:世界最好的聊天软件 编辑:程序博客网 时间:2024/06/07 07:05
class A(object):    m = 20    #实例方法    def __init__(self):        self.x = 10    def fun(self):        print("fun")    #类方法    @classmethod    def class_test(cls):        cls.m = 30    #静态方法    @staticmethod    def static_test():        print("this is test")a = A()a.class_test()print(a.m)print(A.m)a.static_test()A.static_test()a.fun()

output

3030this is testthis is testfun

实例方法可以通过创建的类对象的引用去调用,不能通过类名.实例方法进行调用。实例方法需要传入self参数,即实例对象的引用。
类方法和静态方法可以通过类对象引用和类名去调用。
类方法主要用来修改类变量,当然你也可以通过类名.类变量进行修改,类方法需要传入cls参数,即指向该类,因为类也是对象。
静态方法在括号里不需要传入什么参数,其实就是我们常用的函数,只不过我们在开发的时候用面向对象而不是面向过程,所以最好也把函数包装成方法。静态方法一般和创建的实例对象和该类没有什么关系。

原创粉丝点击