python遍歷類的所有成員

這段代碼自定義了一個類,類包含了兩個成員title和url,在類的內部定義了一個函數list_all_member用於輸出類的所有成員變量及值

# -*- coding: utf-8 -*-
#sharejs.com提供代碼,轉載請註明出處
class Site(object):
    def __init__(self):
        self.title = 'share js code'
        self.url = 'http://www.sharejs.com'
     
    def list_all_member(self):
        for name,value in vars(self).items():
            print('%s=%s'%(name,value))

if __name__== '__main__':
    site = Site()
    site.list_all_member()


#該代碼片段來自於: http://www.sharejs.com/codes/python/8669

結果如下:

url=http://www.sharejs.com
title=share js code

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章