如果属性不存在,请创建属性并为其指定默认值

时间:2015-03-16 21:40:52

标签: python exception-handling try-catch attributeerror

我正在从一本书中学习Python,并且自己编写了一个长测验/类型游戏,最后打印了一个摘要。但是,摘要会查找根据用户做出的选择而不会始终存在的属性。

我已将此抽象为一个基本示例,以显示我想要做的事情。基本上,我只想对每个没有属性的变量运行属性错误检查,创建一个默认值为N / A的属性。

在下面的例子中,我希望它能打印出来:

姓:乔 姓:Bloggs 史密斯测试:N / A. 测试4:N / A

我创建了一个名为CodeCleaner的类,我将用它来设置N / A值,但是非常卡住了!

class QuestionSet(object):
    next_set = 'first_set'

class ClaimEngine(QuestionSet):

    def current_set(self):
        last_set = "blank"
        while_count = int(0)
        quizset = Sets.subsets
        ParentSet = QuestionSet()
        while ParentSet.next_set != last_set and int(while_count)<50:
            quizset[ParentSet.next_set].questioning()
            while_count = while_count+1

class FirstSet(QuestionSet):

    def questioning(self):
        self.value1 = raw_input("Forename:\n")
        QuestionSet.next_set = "second_set"

class SecondSet(QuestionSet):

    def questioning(self):
        self.value2 = raw_input("Surname:\n")
        if self.value2 == "Smith":
            self.value3 = "He's a Smith!"
            self.value4 = "Test val 4"
            QuestionSet.next_set = "summary"
        else: 
            QuestionSet.next_set = "summary"

class CodeCleaner(QuestionSet):

    def questioning(self):
        mapping = Sets() 
        sets = mapping.subsets
        variable_list = {
        [sets['first_set']].value1,
        [sets['second_set']].value2,
        [sets['second_set']].value3,
        [sets['second_set']].value4
        }
        #while key_no < 4:
        #   try:
        #       print variable_list
        #   except AttributeError:


class Summary(QuestionSet):

    def questioning(self):
        mapping = Sets() 
        sets = mapping.subsets
        print "Forename:",sets['first_set'].value1
        print "Surname:",sets['second_set'].value2
        print "Smith Test:",sets['second_set'].value3
        print "Test 4:",sets['second_set'].value4
        exit(0)

class Sets(object):
        subsets = {
        'first_set': FirstSet(),
        'second_set': SecondSet(),
        'summary': Summary()
        }

run = ClaimEngine()
run.current_set()

我觉得这个问题很懒,但是,我已经在这几天摔跤了!任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全采用了您的方法,但您可以在未找到该属性时调用的对象中实现__getattr__方法:

class A(object):
    def __getattr__(self, name):
        print("Creating attribute %s."%name)
        setattr(self, name, 'N/A')

然后:

>>> a = A()
>>> a.a
Creating attribute a.
>>> a.a
'N/A'