Paul's answer स्पष्ट करने के लिए, यहाँ एक सरल उदाहरण है
Class being defined
Instance being created
Instance being created
Instance being created
कोड class
परिभाषा के दायरे में है, लेकिन एक विधि def
inition केवल एक बार चलाता है बाहर, जब वर्ग को परिभाषित किया जाता है।
आप कोड को चलाने के लिए जब भी एक उदाहरण बनाई गई है चाहते हैं, यह __init__
उदाहरण विधि (या, कभी कभी, __new__
वर्ग विधि) में होना चाहिए। हालांकि, ध्यान दें कि यदि आप एक उपवर्ग के लिए __init__
परिभाषित करते हैं, तो आप शायद यह सुनिश्चित करना चाहिए यह भी कहता है कि सुपर क्लास के __init__
:
class AError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs) # call the superclass
print 'error occur' # print your message
यह सुनिश्चित करता है कि उपवर्ग सुपर क्लास के लिए तर्कों का समर्थन करता है; Exception
के मामले में, आप उदा। एक त्रुटि संदेश पारित: यदि आप इसे से परिचित नहीं हैं
>>> 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
*args, **kwargs
वाक्य रचना की एक विवरण के लिए, को देखने के जैसे What does ** (double star) and * (star) do for parameters?। सुपरक्लास विधियों को कॉल करने के लिए आप super
का भी उपयोग कर सकते हैं, उदाहरण देखें Understanding Python super() with __init__() methods।
यह उत्तर बहुत स्पष्ट है, मुझे यह मिल गया है। 3 क्यू बहुत, तो आप की कंद! –