- #1
fog37
- 1,568
- 108
- TL;DR Summary
- Understand the difference between special methods and non-special methods
Hello Forum,
In Python, methods are functions which are defined inside a class. Python has many reserved keywords and built-in functions like print(), add(), type(), etc that we commonly use even when we don't create classes, instances, etc. Whenever we use an operator (like + or - ) or a built-in function like print() or int(), a special method is automatically executed behind the scenes.
In Python, methods are functions which are defined inside a class. Python has many reserved keywords and built-in functions like print(), add(), type(), etc that we commonly use even when we don't create classes, instances, etc. Whenever we use an operator (like + or - ) or a built-in function like print() or int(), a special method is automatically executed behind the scenes.
- In Python, each different type of object (integer, string, function, etc.) has a number of possible special methods that can be called and applied to the object itself based on its type. Special methods are predefined methods (not user-defined methods) can be used inside a user-defined class. I believe that special methods essentially allow us to extend the capabilities of built-in functions/methods so they can be applied to objects that these built-functions/methods are not designed for. Is that correct? For example, dir(5) shows which methods can be used on objects that are integers but not strings. But it may be possible to use one of the listed methods reserved for integers also on strings within a class if we include the special method itself.
- When we create a class and include the method __init__ to initialize the class, the method __init__ automatically runs to create class attributes (the characteristics of any instance of the class) whenever we create an instance from the class. Are all other special methods that we can include in a class definition also executed automatically? On the other hand, non-special methods must be called using the dot notation.
- Other examples of special methods are __main__ , __str__ , __new__ What does the special method __main__ exactly do?
- What about the special method __str__ , which is a method used to convert objects to strings in the context of a class? I think __str__ provides a string representation of the objects generated from the class...Does it automatically get executed whenever we create a class instance generating the name of the object on the screen?