Tuesday, 28 January 2014

PythonFu

Example class in python (implementing some awesome underscore classes (http://www.rafekettler.com/magicmethods.html) :


class test:
    def __init__(self,input1, input2):
        self.var1=input1
        self.var2=input2
    def __call__(self,param):
        print "hello "+param
    def __iadd__(self,val):
        self.var1 += val
        self.var2 += val
        return self
    def __str__(self):
        return str(self.var1)+" "+str(self.var2)

obj=test(1,2) #initialize object obj
obj("san")         #equivalent with obj.__call__("san")
obj += 2      #adding 2 to self.var1 and self.var2
print str(b)  #print out self.var1 and self.var2 by calling __str__



No comments:

Post a Comment