Python 内建函数 - classmethod(function)

Python 的 classmethod 内建函数用于创建类方法,它接收类作为第一个参数而不是实例。类方法可以通过类或实例调用,并在派生类调用时接收派生类对象。区别于 C++ 或 Java 的静态方法,Python 还提供了 staticmethod 用于类似功能。类方法的详细信息可以在 Python 的标准类型层次结构文档中找到。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

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.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

直译

function返回类方法。
一个类方法将类作为第一个隐式参数接收,就好比实例方法接收实例一样。声明一个类方法使用以下语句:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

@classmethod是函数修饰器 — 详情见函数定义。其既可在类上调用(如C.f()),也可在实例上调用(如C().f())。除了类外,将忽略其实例。如果一个类方法被衍生类调用,衍生类对象将作为第一个隐式参数传入。类方法不同于C++或Java的静态方法,如果需要,参见staticmethod()
如果需要获得更多关于类方法的信息,可参考标准类型分层

实例

绑定实例

>>> class 优快云:
    def log(self):
        print('Hello world!')
>>> 优快云.log()
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    优快云.log()
TypeError: log() missing 1 required positional argument: 'self'
>>> c = 优快云()
>>> c.log()
Hello world!
>>> classmethod(c.log())
Hello world!
<classmethod object at 0x03912030>

修饰器绑定类方法

>>> class 优快云:
    @classmethod
    def log(self):
        print('Hello world!')
>>> 优快云.log()
Hello world!
>>> c = 优快云()
>>> c.log()
Hello world!
>>> class foo(优快云):
    def __init__(self):
        print('Loading...')
>>> foo.log()
Hello world!
>>> foo().log()
Loading...
Hello world!

拓展阅读

修饰器
函数定义
staticmethod()
标准类型分层

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值