Demo 通过上面图解我们能很清楚的了解到 python中的类存在四种方法,及其每种方法的用途和说明,
下面通过具体的demo案例加深理解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 class DemoClass : def __init__ (self ): print ("这里测试说明class类中的四个不同类型的方法\n" ) def normal_method (self, *args, **kwargs ): print (" 这个是普通实例方法,需要初始化实例之后调用" ) @staticmethod def static_method (a, b ): print (" 这是类的静态方法(@staticmethod): " , a + b) @classmethod def class_method (cls, *args, **kwargs ): print (" 这是类的类方法(@classmethod): " , args, kwargs) if __name__ == '__main__' : demo = DemoClass() print ("通过实例调用类的实例方法: " ) a = demo.normal_method() print ("通过实例调用类的静态方法: " ) b = demo.static_method(3 , 4 ) print ("通过实例调用类的类方法: " ) c = demo.class_method() print ("------" * 10 ) print ("通过类调用的实例方法: DemoClass.normal_method() 会报错" ) print ("Error: TypeError: normal_method() missing 1 required positional argument: 'self'" ) print ("通过类调用类的静态方法: " ) DemoClass.static_method(3 , 4 ) print ("通过类调用类的类方法: " ) DemoClass.class_method()
结果输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 这里测试说明class类中的四个不同类型的方法 通过实例调用类的实例方法: 这个是普通实例方法,需要初始化实例之后调用 通过实例调用类的静态方法: 这是类的静态方法(@staticmethod): 7 通过实例调用类的类方法: 这是类的类方法(@classmethod): () {} ------------------------------------------------------------ 通过类调用的实例方法: DemoClass.normal_method() 会报错 Error: TypeError: normal_method() missing 1 required positional argument: 'self' 通过类调用类的静态方法: 这是类的静态方法(@staticmethod): 7 通过类调用类的类方法: 这是类的类方法(@classmethod): () {}
classonlymethod 这个是在Django框架
中的,位置位于 django.utils.decorators.py
1 2 3 4 5 6 7 class classonlymethod (classmethod ): def __get__ (self, instance, cls=None ): if instance is not None : raise AttributeError( "This method is available only on the class, not on instances." ) return super ().__get__(instance, cls)
从源码看到它其实就是继承python内置的classmethod
, 只能用于类的调用,不能用于类实例调用。
如果觉得文章对你有所帮忙,欢迎点赞收藏,或者可以关注个人公众号 全栈运维
哦,一起学习,一起健身~