Home  >  Article  >  Backend Development  >  python遍历类中所有成员的方法

python遍历类中所有成员的方法

WBOY
WBOYOriginal
2016-06-06 11:22:202014browse

本文实例讲述了python遍历类中所有成员的方法。分享给大家供大家参考。具体分析如下:

这段代码自定义了一个类,类包含了两个成员title和url,在类的内部定义了一个函数list_all_member用于输出类的所有成员变量及值

# -*- coding: utf-8 -*-
class Site(object):
  def __init__(self):
    self.title = 'jb51 js code'
    self.url = 'http://www.bitsCN.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()

输出结果如下:

url=http://www.bitsCN.com
title=jb51 js code

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn