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

Python @staticmethod, @classmethod, @property

时间:2015-04-13 18:21:34      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

@staticmethod, @classmethod, @property 用法及作用

class Foo(object) :
    def __init__(self) : 
        self._name = "property test"
        print "init"

    def test(self) : 
        print "class method"

    @property
    def name(self) : 
        return self._name

    @staticmethod
    def staticfun() : 
        print "static method function"

    @classmethod
    def classfun(cls) : 
        print "class method function"

if __main__ == __name__ :  
    Foo.staticfun()
    Foo.classfun()

    f = Foo()
    print f.name
    f.test()

 

  • @staticmethod : 静态方法
  • @classmethod : 类方法
  • @property : 将函数以类成员属性方式调用

在C++中,通过类名直接调用的函数称为静态方法,可见@staticmethod和@classmethod没有区别,当然还是有些细微的不同,@classmethod的参数,需要隐式的传递类名.

当然,与C++中是不同的,C++中的成员方法,是不能通过类的实例化对象调用的,直接通过类名调用.

Python @staticmethod, @classmethod, @property

标签:

原文地址:http://www.cnblogs.com/naray/p/4422602.html

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