How can u invoke all the methods of a class at one go without explicit calling each?
# Lets define a class with some methods as: class Nums:
def __init__(self, n): self.val = n def multwo(self): self.val *= 2 def addtwo(self): self.val += 2 def devidetwo(self): self.val /= 2
# Lets create the instance of the class: f = Nums(2)
Now, call each and every methods as in dir(f) list. You should however, take care of methods taking arguments. Example, for init we need to pass args.
for m in dir(f): mymethod = getattr(f, m) if callable(mymethod): if 'init' not in str(mymethod): mymethod() else: pass
print(f.val) => It results 4.
Wonder why ?
This is how the instance stores the methods and properties lists:
['__doc__', '__init__', '__module__', 'addtwo', 'devidetwo', 'multwo', 'val']
So, val = (2+2)/2*2 = 4
Comments