Python constructors and __init__

前端 未结 5 458
耶瑟儿~
耶瑟儿~ 2020-11-30 18:57

Why are constructors indeed called "Constructors"? What is their purpose and how are they different from methods in a class?

Also, can there be more that on

5条回答
  •  感动是毒
    2020-11-30 19:46

    coonstructors are called automatically when you create a new object, thereby "constructing" the object. The reason you can have more than one init is because names are just references in python, and you are allowed to change what each variable references whenever you want (hence dynamic typing)

    def func(): #now func refers to an empty funcion
        pass
    ...
    func=5      #now func refers to the number 5
    def func():
        print "something"    #now func refers to a different function
    

    in your class definition, it just keeps the later one

提交回复
热议问题