Aby wyjaśnić Paul's answer, oto prosty przykład:
class Test(object):
print "Class being defined"
def __init__(self):
print "Instance being created"
for _ in range(3):
t = Test()
Wyjście z tego będzie:
Class being defined
Instance being created
Instance being created
Instance being created
Kod w definicji class
ale poza metoda def
ganization biegnie tylko raz, kiedy klasa jest zdefiniowana.
Jeśli chcesz kod do uruchomienia gdy instancja jest tworzona, powinien on być w __init__
instancji metody (lub Czasami __new__
klasa metoda). Należy jednak pamiętać, że jeśli zdefiniować __init__
dla podklasy, powinieneś upewnić się, że wywołuje także nadklasą na __init__
:
class AError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs) # call the superclass
print 'error occur' # print your message
Gwarantuje to, że podklasa obsługuje argumenty dla nadrzędnej; w przypadku Exception
można np. przekazać komunikat o błędzie:
>>> raise AError("Something went wrong.")
error occur # your message gets printed when the instance is created
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
raise AError("Something went wrong.")
AError: Something went wrong. # the error message passes through to the traceback
Wyjaśnienie składni *args, **kwargs
, jeśli nie są zaznajomieni z tym, patrz na przykład What does ** (double star) and * (star) do for parameters?. Możesz także użyć super
, aby wywołać metody nadklasy, zobacz np. Understanding Python super() with __init__() methods.
Ta odpowiedź jest bardzo jasna, rozumiem. 3Q bardzo, więc kand z was! –