jtwaller jtwaller - 2 months ago 5
Python Question

Unable to successfully call a class string in a for loop

I have a class

class zero:
top = " __ "
mid = "| |"
bot = "|__|"


And I want to use a loop to call the different sections. E.g.:

def printnum(list):
chunks = ['top','mid','bot']
print section # prints "top"
print zero.top # prints " __ "
print zero.section # fails
for section in chunks:
string = ''
for x in list:
if x == '1':
string += getattr(one, section)
elif x == '2':
string += getattr(two, section)
etc....


I must be missing something pretty basic here. Can I use my loop to call the different parts of my class?

Here's a snippet of intended functionality:

>>Enter the number you would like printed: 21
__ __
__||__
__| __|

Answer

Your zero class doesn't have an attribute called section, what you can do instead is to use getattr which accepts a string (second argument) as the object property to get, like this:

class zero:
  top = " __ "
  mid = "|  |"
  bot = "|__|"

chunks = ['top','mid','bot']
for section in chunks:
    print section       # prints  "top"
    print zero.top      # prints  " __ "
    print getattr(zero, section)

Which tells python that you want to get the attribute (all the items in your list when you're looping through it) your object zero.

getattr also takes a third argument that would be returned if the object doesn't have that property.

getattr(zero, section, 'Not Found')