无法在for循环中成功调用类字符串

时间:2016-09-16 23:12:42

标签: python

我有一个班级

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

我想用一个循环来调用不同的部分。 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....

我必须遗漏一些非常基本的东西。我可以使用我的循环来调用我班级的不同部分吗?

以下是预期功能的片段:

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

1 个答案:

答案 0 :(得分:1)

您的zero类没有名为section的属性,而您可以使用getattr接受字符串(第二个参数)作为对象属性得到,像这样:

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)

告诉python你想要获取属性(当你循环遍历列表中的所有项目时)你的对象zero

getattr还会获取第三个参数,如果该对象没有该属性,则会返回该参数。

getattr(zero, section, 'Not Found')