Python: multiple calls to __init__() on the same instance
-
23-09-2019 - |
문제
The __init__()
function gets called when object is created.
Is it ok to call an object __init__()
function again, after its been created?
instance = cls(p1=1, p2=2)
# some code
instance.__init__(p1=123, p2=234)
# some more code
instance.__init__(p1=23, p2=24)
why would anyone wanna call __init__()
on an object that is already created?
good question. i wanna re-initialize the instance's fields.
해결책
일반적으로 탐색 경로 제어 (SP 2010의 맨 위에있는 폴더) 또는 브라우저 백 버튼이 접근 방식입니다.그러나 나는 사용자 정의 목록 readcrumb을 목록보기 위에 또는 아래에 놓아야 할 사용자 정의 목록 reportcrumb을 작성했습니다.그러나 그것은 어떤 사용자 정의 코딩 (WebPart 또는 콘텐츠 편집기 웹 파트의 JavaScript에 의한) 을 의미합니다.
다른 팁
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)
As far as I know, it does not cause any problems (edit: as suggested by the kosher usage of super(...).__init__(...)
), but I think having a reset()
method and calling it both in __init__()
and when you need to reset would be cleaner.