Python - 静态方法, 类方法

# 类的方法有三种:
# 1) 一是通过def定义的 普通的一般的,需要至少传递一个参数,一般用self,这样的方法必须通过一个类的实例去访问,类似于c++中通过对象去访问
# 2) 在def前面加上@classmethod,这种类方法的一个特点就是可以通过类名去调用,但是也必须传递一个参数,一般用cls表示class,表示可以通过类直接调用
# 3) 在def前面加上@staticmethod,这种类方法是静态的类方法,类似于c++的静态函数,他的一个特点是参数可以为空,同样支持类名和对象两种调用方式

代码示例:


class A(object):
    member = 'this is a test'
    def __init__(self):
        pass

    @classmethod # 类方法
    def print1(cls):
        print(cls.member)

    def print2(self):
        print(self.member)

    @staticmethod  # 静态方法
    def print3():
        print('static method')

    @staticmethod  # 静态方法
    def print4(cls):
        print('static method', cls.member, cls)

if __name__ == "__main__":
    a = A()
    A.print1()
    a.print2()
    A.print3()
    A.print4(A)
    a.print4(A)
    a.print4(a)

----
this is a test
this is a test
static method
static method this is a test <class '__main__.A'>
static method this is a test <class '__main__.A'>
static method this is a test <__main__.A object at 0x102a08908>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容