码迷,mamicode.com
首页 > 编程语言 > 详细

Python classmethod 修饰符

时间:2018-04-17 11:57:53      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:method   func   类方法   usr   pretty   对象   assm   方法   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
foo

Python classmethod 修饰符

标签:method   func   类方法   usr   pretty   对象   assm   方法   python   

原文地址:https://www.cnblogs.com/mabingxue/p/8862104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!