python - Where attribute does not exist, create an attribute and give it a default value -
i learning python out of book , have written myself long quiz/type game prints summary @ end. however, summary looks attributes not exist depending on choices have been made user.
i have abstracted basic example show trying do. essentially, want run attribute error check, every variable not have attribute, create attribute default value of n/a.
in below example, want print:
forename: joe surname: bloggs smith test: n/a test 4: n/a
i created class called codecleaner going use set n/a values, got stuck!
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 , 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 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()
i feel quite lazy asking question, however, i've been wrestling few days now! appreciated.
i'm not sure go approach, can implement __getattr__
method in object called when attribute not found:
class a(object): def __getattr__(self, name): print("creating attribute %s."%name) setattr(self, name, 'n/a')
then:
>>> = a() >>> a.a creating attribute a. >>> a.a 'n/a'
Comments
Post a Comment