Python的实例方法,类方法和静态方法的区别

OOP是一种编程思想,各种语言对这种思想的实践都不尽相同,这体现在他们的语法当中

class Test(object):

    class_name = "Test"

    def __init__(self):
        self.x = 5


    #实例方法
    def test01(self):
        print("InstanceMethod called!")
        print(self.x)

    #类方法
    @classmethod
    def test02(cls):
        print("ClassMethod called!")
        print(cls.class_name)

    #静态方法
    @staticmethod
    def test03():
        print("StaticMethod called!")

if __name__ == "__main__":
    T = Test()
    # test01的两种调用方式
    T.test01()
    Test.test01(T)

    # test02的调用方式
    T.test02()

    # test03的调用方式
    T.test03()
    Test.test03()

执行结果:

InstanceMethod called!
5
InstanceMethod called!
5
ClassMethod called!
Test
StaticMethod called!
StaticMethod called!

实例方法就是普通的类的方法
类方法只能访问类的属性不能访问实例的属性
静态方法不能访问类和实例属性,就是在类型的一般函数

例子里。普通方法和静态方法都有两种调用方式,但是前者总要传入实例,但是后者不需要,请注意甄别。

猜你喜欢

转载自blog.csdn.net/github_34777264/article/details/80308719