• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python类的四种方法(方法、静态方法、类方法)

武飞扬头像
eaglecolin
帮助5

学新通


Demo

通过上面图解我们能很清楚的了解到 python中的类存在四种方法,及其每种方法的用途和说明,

下面通过具体的demo案例加深理解

#!/usr/bin/env python
# encoding: utf-8
# Author: Colin
# Date: 2022-08
# Desc: 举例说明class类中的四类不同类型的方法
# 

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'")
    # DemoClass.normal_method()
    print("通过类调用类的静态方法:  ")
    DemoClass.static_method(3, 4)
    print("通过类调用类的类方法: ")
    DemoClass.class_method()
学新通

结果输出

这里测试说明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

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, 只能用于类的调用,不能用于类实例调用。


如果觉得文章对你有所帮忙,欢迎点赞收藏,或者可以关注个人公众号 全栈运维 哦,一起学习,一起健身~

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfgicbh
系列文章
更多 icon
同类精品
更多 icon
继续加载