class Custom(Exception):
def __init__(self): # Corrected from __int__ to __init__
super().__init__()
print("make the create of Error")
def __str__(self):
return "create Error"
raise Custom()
Your code defines a custom exception class named `Custom`, intended to demonstrate custom exception handling in Python. However, there's a small typo in your class definition that affects its intended functionality. Let's review and correct the code:
### Original Code Review
1. **Typo in Initializer Method**:
- Your code defines a method named `__int__` instead of `__init__`. The `__int__` method is not called when an instance is created; it's a special method intended for converting an object to an integer, which is not typically used in exception classes. The correct method name for initializing objects is `__init__`.
2. **`__str__` Method**:
- This method is correctly defined. It overrides the default string representation of the object, so when you print the exception or convert it to a string using `str()`, it will return "create Error".
3. **Raising the Custom Exception**:
- The `raise Custom` statement correctly raises an instance of the `Custom` exception. However, due to the typo in the initializer, the intended print statement "make the create of Error" won't execute upon instantiation.
### Explanation of the Corrected Code
- **`__init__(self):`** Now correctly defines the initializer method. When a `Custom` exception is instantiated (which happens implicitly when you `raise` it), it will print "make the create of Error" to the console.
- **Raising the Exception**: The `raise Custom()` statement (parentheses are optional here but added for clarity) creates an instance of `Custom`, triggering the corrected `__init__` method and subsequently raising the exception. The program will halt at this point unless the exception is caught in a try-except block.
- **String Representation (`__str__`)**: If the exception is caught and printed, or otherwise converted to a string, "create Error" will be the result, thanks to the overridden `__str__` method.
### Conclusion
With the corrected initializer method name, the `Custom` exception class will behave as intended, demonstrating both the instantiation process of custom exceptions and customizing their string representations.
'개념 > 혼자 공부하는 파이썬' 카테고리의 다른 글
python) Class Definitions and Inheritance (1) | 2024.10.31 |
---|---|
python) Put only things that can be converted to numbers into a list (2) | 2024.10.30 |
python) size comparison function (2) | 2024.10.28 |
python) Declare a function inside a class (0) | 2024.10.27 |
python) class parameter (0) | 2024.10.26 |