Python 内建函数 - classmethod(function)

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

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()
标准类型分层

<think>我们正在回答用户关于Python内置函数类型的问题。根据引用[1],Python内置函数是预先定义在标准模块builtins中的函数,我们可以直接使用它们。用户要求的是内置函数的类型列表,但需要注意的是,Python内置函数本身是函数对象,它们属于内置函数类型(built-infunction)。不过,用户可能想知道内置函数有哪些,即列出所有内置函数的名称。但是,引用[1]并没有提供完整的列表,因此我们需要根据Python标准知识来回答。Python有多个版本,但内置函数在不同版本中相对稳定。这里我们以Python3.8及以上版本为例。实际上,Python的内置函数没有明确的“类型”分类(如字符串函数、数学函数等)是官方定义的,但我们可以按照功能进行归类。不过,用户可能只是想要一个列表,或者按照功能分类的列表。考虑到用户的问题“请问Python内置函数类型列表”,我们可以理解为用户想要知道Python有哪些内置函数,以及它们的功能分类。因此,我们可以这样回答:1.首先列出所有内置函数的名称(按字母顺序)。2.然后,可以按照功能进行分类,如数学运算、类型转换、序列操作等。但注意,引用[1]中提到了我们可以通过`dir(__builtins__)`来查看内置函数和类型,但这样会列出很多内置类型(如int,str)和异常(如Exception),而不仅仅是函数。因此,我们需要筛选出函数。我们可以这样获取内置函数列表(在Python交互环境中):```pythonimportbuiltins#获取所有内置函数的名字builtin_funcs=[namefornameindir(builtins)ifcallable(getattr(builtins,name))andnotname.startswith('__')]```但注意,有些内置函数是以双下划线开头和结尾的(如`__import__`),通常我们使用的不带双下划线的函数名(如`abs`)是主要的内置函数。实际上,Python官方文档中有一个内置函数列表:https://docs.python.org/3/library/functions.html我们可以参考这个列表。下面,我们将按照功能分类列出一些常用的内置函数:###数学运算相关-`abs(x)`:返回绝对值-`divmod(a,b)`:返回商和余数-`max(iterable,*[,key,default])`/`max(arg1,arg2,*args[,key])`:返回最大值-`min(iterable,*[,key,default])`/`min(arg1,arg2,*args[,key])`:返回最小值-`pow(base,exp[,mod])`:幂运算-`round(number[,ndigits])`:四舍五入-`sum(iterable,/,start=0)`:求和###类型转换-`bool(x)`:转换为布尔值-`int(x,base=10)`:转换为整数-`float(x)`:转换为浮点数-`str(object='')`:转换为字符串-`complex(real,imag=0)`:创建复数-`bin(x)`:整数转二进制字符串-`hex(x)`:整数转十六进制字符串-`oct(x)`:整数转八进制字符串###序列操作-`all(iterable)`:所有元素为真则返回True-`any(iterable)`:任一元素为真则返回True-`enumerate(iterable,start=0)`:返回枚举对象-`filter(function,iterable)`:过滤序列-`map(function,iterable,...)`:映射函数到序列-`len(s)`:返回长度-`range(start,stop[,step])`:生成整数序列-`reversed(seq)`:反转序列-`sorted(iterable,*,key=None,reverse=False)`:排序-`zip(*iterables)`:将多个序列打包成元组###输入输出-`input([prompt])`:获取用户输入-`print(*objects,sep='',end='\n',file=sys.stdout,flush=False)`:打印输出###对象操作-`id(object)`:返回对象标识符-`isinstance(object,classinfo)`:检查对象是否为类的实例-`issubclass(class,classinfo)`:检查类是否为子类-`type(object)`:返回对象类型-`dir([object])`:返回对象的属性列表-`hasattr(object,name)`:检查对象是否有属性-`getattr(object,name[,default])`:获取对象属性-`setattr(object,name,value)`:设置对象属性-`delattr(object,name)`:删除对象属性-`callable(object)`:检查对象是否可调用-`hash(object)`:返回对象的哈希值-`help([object])`:帮助信息-`repr(object)`:返回对象的可打印字符串(供解释器读取)-`format(value[,format_spec])`:格式化值-`vars([object])`:返回对象的`__dict__`###编译与执行-`compile(source,filename,mode,flags=0,dont_inherit=False,optimize=-1)`:编译源代码-`eval(expression,globals=None,locals=None)`:执行表达式-`exec(object,globals=None,locals=None)`:执行代码###其他-`open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)`:打开文件-`staticmethod(function)`:将函数转换为静态方法-`classmethod(function)`:将函数转换为类方法-`property(fget=None,fset=None,fdel=None,doc=None)`:创建属性-`super([type[,object-or-type]])`:调用父类方法-`memoryview(object)`:创建内存视图-`iter(object[,sentinel])`:返回迭代器-`next(iterator[,default])`:获取迭代器的下一个元素-`slice(stop)`/`slice(start,stop[,step])`:创建切片对象-`breakpoint(*args,**kws)`:设置断点(Python3.7新增)-`ascii(object)`:返回对象的ASCII表示以上分类仅供参考,有些函数可能同时属于多个类别。注意:在Python中,内置函数和内置类型是分开的,比如`str`、`list`、`dict`等既是类型也是可调用对象(它们被用来创建该类型的实例),因此在上面的列表中我们包含了这些。但是,有些内置类型(如`int`,`str`,`list`,`tuple`,`dict`,`set`)通常也被视为内置函数,因为它们可以用于转换或创建对象。因此,在回答中,我们可以先给出一个总列表(按字母顺序),然后给出分类。由于用户要求“类型列表”,我们可以理解为按功能分类。但是,考虑到引用[
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值