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

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):
        pass

class Sub(Super,ListInstance):
    def __init__(self):
        Super.__init__(self)
        self.data2 = 'eggs'
        self.data3 = 42

    def spam(self):
        pass

if __name__ == '__main__':
    X = Sub()
    print(X)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值