Albert
Albert

Reputation: 76

Iteration on members and attributes on a Class

I understand how to create an unsophisticated class based on examples culled from the Web but I hit a wall when trying to access the members on it, to wit:

Let's say this is my class:

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

To create and object I use:

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

and to create a new attribute for lemon I use:

lemon.peel = 'easy'

I would like to define a method inside (or outside) of the class that will be called printall that will iterate though all the existing members of the class and print all of them with their attributes even if the attributes are variable (more than de ones initially defined). I think this is called "overloading" but I am not sure of the proper terminology.

Upvotes: 1

Views: 115

Answers (3)

sameera sy
sameera sy

Reputation: 1718

And if you're not sure then you can use the below loop to find details of all members

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)

Upvotes: 1

sameera sy
sameera sy

Reputation: 1718

perhaps this is what you're looking for, though the printall method is not a part of the class, it is able to access the class when you pass an object to it and the following code should print the attribute name and value of the object lemon in Fruits class.

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)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124748

The term you are looking for is type introspection. Overloading is something entirely different, where you provide different implementations of a method.

You can access all instance attributes with the var() function; it returns a dictionary you can then iterate over to print your variables:

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

Upvotes: 2

Related Questions