python - Using options (argparse) in method within a method within a class -


i have class init , 2 other methods. within latter 2 methods, additional methods make appropriate calculations. want access , use options command line arguments (using argparse). appropriate way use options when have method within method within class? structure of code :

class p(object):     def __init__(self, a, options):         self.a =         self.b = none         self.weight = none         self.score = none         self.firstscore = none      def calc_score(self, options):         self.b = #method calculate float, using string self.a (raw value)          def calc_weight(self, options):             if float(self.b) > options.valuefromcommandline:                 self.b_weight == 0             else:                 self.b_weight == 100             return self.b_weight          self.weight = (self.calc_weight(self.b))         self.score = self.weight * options.valuefromcommandline         self.firstscore = self.score * constant          return self.firstscore 

i continue attributeerror: 'p' object has no attribute 'valuefromcommandline'.

when change method calls options, nameerror: global name 'b' not defined or

typeerror: 'calc_weight' takes 1 argument (2 given)

can please appropriate code structure here, have ability use options within methods within class? or appropriate structure better in case.

the attributeerror: 'p' object has no attribute 'valuefromcommandline' error means ever giving parameter calc_score options argument not have attribute.

but don't tell how call method, or how how create p object in first place.

calc_weight function defined within calc_score. not p method. call calc_weight(self, options).

i rewrite part as:

def calc_weight(b, value):     # no use self here     if float(b) > value:         b_weight == 0     else:         b_weight == 100     return b_weight self.weight = self.calc_weight(self.b, options.valuefromcommandline) 

your question incomplete. ideally should runnable clip - can cut-and-paste, if produces error message.

why tag argparse (and use in title) don't give parser definition? suspect options result of parser.parse_args() call, without seeing parser definition, or command line, can't sure.

you might define calc_score take value, rather whole options object (much did calc_weight). looks attribute of options use here.

this i'd expect working code like:

 import argparse  # p definition can imported without running  class p(object):      ....   if __name__ == '__main__':      # block used when called script      parser = argparse.argumentparser()      parser.add_argument('value', type=int, help='command line positional argument')      # type=int because used later in numeric comparison      ....      args = parser.parse_args()       p = p('10')  # p a=`10` string      print(p.calc_score(, args.value))      # or p.calc_score(args) 

Comments