Python 实例方法、静态方法、类方法 (二十)

来源:互联网 发布:最早的网络搜索引擎 编辑:程序博客网 时间:2024/06/04 23:21
实例方法
参数带self的方法,实例化对象可使用
class Test(object):    def __init__(self):        self.a = "Hello world!"          def test(self):        print self.a#实例方法必须在类实例化后使用A = Test()A.test() 


静态方法
静态方法是一种普通函数,就位于类定义的命名空间中,它不会对任何实例类型进行操作。使用装饰器@staticmethod定义静态方法。类对象和实例都可以调用静态方法

class Test(object):    def __init__(self):pass         @staticmethod     def test(a):        print a#静态方法可以在未实例化的情况下使用Test.test("Hello world!")A = Test()A.test("Hello world!") 

类方法
类方法是将类本身作为对象进行操作的方法。类方法使用@classmethod装饰器定义,其第一个参数是类,约定写为cls。类对象和实例都可以调用类方法()
class Test(object):    def __init__(self):pass         @classmethod      def test(cls,a ):        print a#类方法可以在未实例化的情况下使用Test.test("Hello world!")A = Test()A.test("Hello world!") 


0 0
原创粉丝点击