【python】类中的self

在python的类中,经常会写self,代表对象自己。如下例:

#coding=utf-8

class Foo:
    def __init__(self, name):
        self.name = name
    def hi(self):
        print self.name
      
if __name__ == '__main__':
    foo01 = Foo('letian')
    foo01.hi()
    print type(Foo)
    print type(foo01)
    print id(Foo)
    print id(foo01)

 

实际上,这只是一种约定的习惯写法。其实不写self,写其他的也是能够正确运行的。比如下面这样:

#coding=utf-8

class Foo:
    def __init__(a, name):
        a.name = name
    def hi(b):
        print b.name
      
if __name__ == '__main__':
    foo01 = Foo('letian')
    foo01.hi()
    print type(Foo)
    print type(foo01)
    print id(Foo)
    print id(foo01)

 

posted @ 2016-10-25 21:16  匡子语  阅读(254)  评论(0编辑  收藏  举报