博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python classmethod类方法修饰符
阅读量:4147 次
发布时间:2019-05-25

本文共 1142 字,大约阅读时间需要 3 分钟。

classmethod 修饰符将函数转换为类方法。类方法将类作为隐式第一个参数接收,就像实例方法接收实例一样。

类方法声明格式:

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

它可以在类(例如C.f())或实例(例如C().f())上调用。实例被忽略,但它的类除外。如果为派生类调用类方法,则派生类对象作为隐含的第一个参数传递。

类方法第一个参数cls表示自身类,可以来调用自身类的属性,类的方法,实例化对象等。
实例演示:
classmethod.py内容如下

#!/usr/bin/python# -*- coding: UTF-8 -*-class C(object):    y = 10    def func1(self):     #需要实例化才能调用        print('func1')    @classmethod    def func2(cls):      #不需要实例化就能调用        print("func2 start")        print("C.y =", cls.y)    #类属性不需要实例化就能调用        new_cls = cls()        new_cls.func1()        try:            cls.func3()        except TypeError as e:           print(e)        print("func2 end")            def func3():         #python2需要实例化之后调用,python3不需要实例化就能调用        print("func3")C.func2()X.func2()

python2和python3的运行结果如下

[sudley@CSDN /home/Sudley/Python]#python2 classmethod.pyfunc2 start('C.y =', 10)func1unbound method func3() must be called with C instance as first argument (got nothing instead)func2 end[sudley@CSDN /home/Sudley/Python]#python3 classmethod.pyfunc2 startC.y = 10func1func3func2 end[sudley@CSDN /home/Sudley/Python]#

转载地址:http://zyiti.baihongyu.com/

你可能感兴趣的文章
Template模式
查看>>
Observer模式
查看>>
高性能服务器设计
查看>>
性能扩展问题要趁早
查看>>
MySQL-数据库、数据表结构操作(SQL)
查看>>
OpenLDAP for Windows 安装手册(2.4.26版)
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>
Pentaho 开发: 在eclipse中构建Pentaho BI Server工程
查看>>
JSP的内置对象及方法
查看>>
android中SharedPreferences的简单例子
查看>>
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Spring MVC和Struts2的比较
查看>>
Hibernate和IBatis对比
查看>>
Spring MVC 教程,快速入门,深入分析
查看>>
Android 的source (需安装 git repo)
查看>>
Commit our mod to our own repo server
查看>>
LOCAL_PRELINK_MODULE和prelink-linux-arm.map
查看>>
Simple Guide to use the gdb tool in Android environment
查看>>