Python classmethod装饰器原理及用法解析

作者:lincappu 时间:2023-02-14 06:59:01 

英文文档:

classmethod(function)

Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

标记方法为类方法的装饰器

说明:

1. classmethod 是一个装饰器函数,用来标示一个方法为类方法

2. 类方法的第一个参数是类对象参数,在方法被调用的时候自动将类对象传入,参数名称约定为cls

3. 如果一个方法被标示为类方法,则该方法可被类对象调用(如 C.f()),也可以被类的实例对象调用(如 C().f())


>>> class C:
 @classmethod
 def f(cls,arg1):
   print(cls)
   print(arg1)

>>> C.f('类对象调用类方法')
<class '__main__.C'>
类对象调用类方法

>>> c = C()
>>> c.f('类实例对象调用类方法')
<class '__main__.C'>
类实例对象调用类方法

4. 类被继承后,子类也可以调用父类的类方法,但是第一个参数传入的是子类的类对象


>>> class D(C):
 pass

>>> D.f("子类的类对象调用父类的类方法")
<class '__main__.D'>
子类的类对象调用父类的类方法

来源:https://www.cnblogs.com/lincappu/p/8145372.html

标签:Python,classmethod,装饰器
0
投稿

猜你喜欢

  • HTML标签tbody的用法

    2009-11-02 10:11:00
  • Python scrapy爬取小说代码案例详解

    2021-09-18 17:03:52
  • OL IE Bug

    2009-09-09 16:25:00
  • php函数之strtr和str_replace的用法详解以及效率分析

    2023-06-02 14:04:18
  • Python定时任务APScheduler安装及使用解析

    2023-07-15 02:49:00
  • Python实现国外赌场热门游戏Craps(双骰子)

    2023-12-13 23:22:21
  • PHP levenshtein()函数用法讲解

    2023-06-01 15:20:29
  • Python 异步如何使用等待有时间限制协程

    2022-02-12 09:29:28
  • SQL语句中的一些特殊参数如何用变量来代替

    2008-03-14 07:44:00
  • js实现鼠标感应向下滑动隐藏菜单的方法

    2024-05-02 17:23:21
  • Python UnicodedecodeError编码问题解决方法汇总

    2023-10-07 09:28:20
  • oracle跨库查询的方法

    2023-07-18 03:15:35
  • Python编程实现二分法和牛顿迭代法求平方根代码

    2022-01-03 12:24:46
  • Linux下Python获取IP地址的代码

    2023-02-27 10:30:07
  • php session安全问题分析

    2023-11-15 06:45:29
  • Python Tkinter实现简易计算器功能

    2023-08-08 09:53:30
  • 超详细,教你用python语言实现QQ机器人制作教程

    2023-10-05 10:12:53
  • flash与asp/php/asp.net通信的方法第1/3页

    2023-11-15 03:43:03
  • Javascript 文件夹选择框的两种解决方案

    2024-04-16 09:50:46
  • PHP OPP机制和模式简介(抽象类、接口和契约式编程)

    2023-11-21 10:53:53
  • asp之家 网络编程 m.aspxhome.com