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

python 类中staticmethod,classmethod,普通方法

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

标签:.com   ges   span   on()   utf-8   author   示例   ini   alt   

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,普通方法

标签:.com   ges   span   on()   utf-8   author   示例   ini   alt   

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

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