Python: multiple calls to __init__() on the same instance

后端 未结 3 1548
一个人的身影
一个人的身影 2021-02-19 01:07

The __init__() function gets called when object is created. Is it ok to call an object __init__() function again, after its been created?



        
3条回答
  •  臣服心动
    2021-02-19 01:37

    You can, but it's kind of breaking what __init__ is intended to do. A lot of Python is really just convention, so you might as well follow then and expect __init__ to only be called once. I'd recommend creating a function called init or reset or something which sets the instance variables, use that when you want to reset the instance, and have __init__ just call init. This definitely looks more sane:

    x = Pt(1,2)
    x.set(3,4)
    x.set(5,10)
    

提交回复
热议问题