oop - How to create a static local variable in python instance method? -
oop - How to create a static local variable in python instance method? -
i'm coming c/c++ world , having hard time making of oop analogies in python. wrapped script in class , error in log()
'private' instance method:
attributeerror: 'instancemethod' object has no attribute 'counter'
def __log(self, contents): sys.stdout.write(contents) # append writes after first if not hasattr(self.__log, "counter"): self.__log.counter = 1 f = open(self.output_filepath, 'w') else : f = open(self.output_filepath, 'a') f.write(contents) f.close()
python doesn't have static local variables. best solution want utilize class attribute:
class withlog(object): opened = false def log(self, contents): sys.stdout.write(contents) mode = "a" if self.__class__.opened else "w" open(self.output_filepath, mode) f: f.write(contents) self.__class__.opened = true
of course, might improve not open , close log file....
python oop
Comments
Post a Comment