Python参考手册
Python classmethod 修饰符
Python classmethod 修饰符
Python classmethod 修饰符
Python 内置函数描述
classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
语法
classmethod 语法:
classmethod
参数
- 无。
返回值
返回函数的类方法。
实例
以下实例展示了 classmethod 的使用方法:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # 调用 foo 方法
A.func2() # 不需要实例化
输出结果为:
func2 1 fooPython 内置函数
Python classmethod 修饰符 |
---|
Python 是一种面向对象的解释型计算机程序设计语言,由荷兰人 Guido van Rossum 于1989年发明,第一个公开发行版发行于1991年。 Python 是纯粹的自由软件, 源代码和解释器 CPython 遵循 GPL 协议。Python 语法简洁清晰,特色之一是强制用空白符( white space )作为语句缩进。
主页 | https://www.python.org/ |
源码 | https://github.com/python/cpython |
版本 | 2.7 |
发布版本 | 2.7.13 |