[Python]How to use magic methods in Python?


In this article, i write a simple code example to explore how to use super,new,init and str magic method in Python.

class MainClass(object):
    def __new__(cls,*args,**kwargs):        
        print 'this is the new method'
        return super(MainClass,cls).__new__(cls, *args,**kwargs)
        #return object.__new__(cls,*args,**kwargs)
    def __init__(self):
        print 'this is init method'    
    def __str__(self):
        return 'test the string method'    
def main():
    #help(object)
    instance = MainClass()
    print str(instance)
        
if __name__ == '__main__':    
    main()


评论关闭