对类的成员和属性进行迭代



我知道如何根据从网上挑选的例子创建一个简单的类,但我在尝试访问它上的成员时遇到了困难,也就是说:

假设这是我的课:

class Fruit(object):
    def __init__(self, name, color, flavor):
        self.name = name
        self.color = color
        self.flavor = flavor
    def description(self):
        print('I am a %s %s and my taste is %s and I am %s' % self.color, self.name, self.flavor))

创建和对象我使用:

lemon = Fruit('lemon', 'yellow', 'sour')

并为柠檬创建一个新的属性,我使用:

lemon.peel = 'easy'

我想在类的内部(或外部)定义一个方法,该方法将被称为printall,它将遍历类的所有现有成员,并打印所有成员及其属性,即使属性是可变的(比最初定义的de多)。我认为这叫做"过载"但我不确定合适的术语。

您要查找的术语是类型的内省。重载是完全不同的,在重载中,您可以提供不同的方法实现。

使用var()函数可以访问所有实例属性;它返回一个字典,然后您可以迭代以打印变量:

def printall(self):
    for name, value in vars(self).items():
        print('self.{} = {!r}'.format(name, value))

如果您不确定,可以使用下面的循环查找所有成员的详细信息

import gc
#garbage collector should do the trick
#all the other code
for obj in gc.get_objects():
    if isinstance(obj, Fruit):
        print "object name :",obj.name
        printall(obj)

也许这就是您想要的,尽管printall方法不是类的一部分,但当您将对象传递给它时,它能够访问该类,并且下面的代码应该在Fruits类中打印对象柠檬的属性名称和值。

def printall(lemon):
    for a in dir(lemon):
        if not a.startswith('__') :
            print a,":",getattr(lemon, a)

#rest of the code
lemon = Fruit('lemon', 'yellow', 'sour')
lemon.peel = 'easy'
printall(lemon)