首页 > 编程语言 > 详细

python 类中staticmethod,classmethod,普通方法

时间:2016-11-19 12:14:16      阅读:199      评论:0      收藏:0      [点我收藏+]

1.staticmethod:静态方法
和全局函数类似,但是通过类和对象调用。

2.classmethod:类方法
和类相关的方法,第一个参数是class对象(不是实例对象)。
在python中class也是一个真实存在于内存中的对象,不同于其他语言只存在于编译期间。

3.普通方法
和实例相关的方法,通过类实例调用。

4.代码示例

#coding:utf-8
‘‘‘
Created on 2015年5月29日
@author: canx
‘‘‘

class Person:
    def __init__(self):
        print "init"

    @staticmethod
    def sayHello(hello):
        print "sayHell %s"%(hello)

    @classmethod
    def introduce(cls,hello):
        print "introduce %s"%(hello)

    def hello(self,hello):
        print "hello %s"%(hello)

def main():
    Person.sayHello("test")
    Person.introduce("test")
    p=Person()
    p.hello("test")

if __name__==__main__:
    main()

输出结果:

技术分享

python 类中staticmethod,classmethod,普通方法

原文:http://www.cnblogs.com/shijingjing07/p/6079995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!