I would like to use string interpolation within instance methods: but am unsure how to access instance variables.
Here is the basic class declaration including the constructor:
class Validation:
def __init__(self, name, type, count, script):
self.name = name
self.type = type
self.count = count
self.script = script
And here is where we want to access the list of variables. Note "globals()" is not correct..
def __repr__(self):
return "%(self.name)s: %(self.type)s that expects %(self.count)s Rows [%(self.script)s]" %self.__dict__
But that gives exception
(<type 'exceptions.KeyError'>, KeyError('self.name',), None)
So the question is: what should be used in place of %self.dict here?
self.:"%(name)s: %(type)s that expects %(count)s Rows [%(script)s]" % self.__dict__.vars(self)is a little nicer on the eyes thanself.__dict__.return "%s: %s that expects %s Rows [%s]" % (self.name, self.type, self.count, self.script)? It's as short as what you've already written and more refactor-friendly.__dict__directly. If one of those is apropertyinstead of an instance attribute (or if the class uses__slots__), the variable won't be in__dict__. This is also true of usingvars, actually. It really is best to just explicitly pass in the variables you want to use.