简体   繁体   中英

Will __init__ be called automatically for every method call?

class linkedlist:
    def __init__(self,value):
        self.head={'value':value,'next':None}
        self.tail=self.head
        self.length=1
    def append(self,value):
        self.newnode={'value':value,'next':None}
        self.tail['next']=self.newnode
        self.tail=self.newnode      
        self.length+=1
if __name__=='__main__':
    l=linkedlist(10)
    l.append(5)
    l.append(16)

The code is working fine but I have doubts about how __init__ works. Will __init__ be called for every function call? Its quite a bit confusing because I am changing the tail and the head value.

How does the main function works here?

The main use of init function is for initialization. It is called when we make an object, at the same time all values mentioned in the function will be initialized and associate with the object. The best way to find out how the function is working or how the whole code is working sequentially, just try to add print function in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM