用__dict__列出实例属性的通用工具

来源:互联网 发布:什么叫懂电脑知乎 编辑:程序博客网 时间:2024/06/09 17:15

lister.py

class ListInstance:    '''    Mix-in class that provides a formatted print() or str() of    instances via inheritance of __str__,coded here;displays    instance attrs only;self is the instance of lowest class;    use __x names to avoid clashing with client's attrs    '''    def __str__(self):        return '<Instance of %s,address %s:\n%s>'%(            self.__class__.__name__,            id(self),            self.__attrnames())    def __attrnames(self):        result = ''        for attr in sorted(self.__dict__):            result += '\tname %s=%s\n'%(attr,self.__dict__[attr])        return result

**测试**1:

D:\Python34\learn>python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (In
tel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.

from lister import ListInstance
class Spam(ListInstance):
… def init(self):self.data1=’food’

x = Spam()
print(x)
Instance of Spam,address 16036592:
name data1=food

x
main.Spam object at 0x00F4B2F0
str(x)
‘Instance of Spam,address 16036592:\n\tname data1=food\n’

>

**测试**2

from lister import *class Super:    def __init__(self):        self.data1 = 'spam'    def ham(self):        passclass Sub(Super,ListInstance):    def __init__(self):        Super.__init__(self)        self.data2 = 'eggs'        self.data3 = 42    def spam(self):        passif __name__ == '__main__':    X = Sub()    print(X)

<\Instance of Sub,address 21706416:
name data1=spam
name data2=eggs
name data3=42
>