使用dir列出包含继承的属性

来源:互联网 发布:算法和程序的关系 编辑:程序博客网 时间:2024/05/18 20:08

lister1.py

class ListInherited:    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 dir(self):            if attr[:2] == '__' and attr[-2:] == '__':                result += '\tname %s=<>\n'%attr            else:                result +='\tname %s=%s\n'%(attr,getattr(self,attr))        return result

测试:

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