0

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
 __  __
 __||__
 __| __|
jtwaller
  • 120
  • 7
  • 1
    Just a suggestion: Don't make a `Zero` class (and other number-named classes). Create a class called something like `BigASCII`, which has `top`, `mid` and `bot` fields, then just create an instance of the class for each number. That will save you from needing to create a ton of classes that will all do essentially the same thing. – Carcigenicate Sep 17 '16 at 00:07

1 Answers1

1

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')
danidee
  • 9,298
  • 2
  • 35
  • 55