본문 바로가기
Python(Eng. ver)

17. Special Method

by 곽정우 2024. 3. 19.

1. Special Methods

Special methods, also known as magic methods in Python, are methods that have names starting and ending with double underscores (__). These methods are automatically called by the Python interpreter when certain operators or built-in functions are used.

  • init : This method is called when an object is created. It is used to initialize the object's attributes.
  • str : This method is called when an object is converted to a string. It is used to return a string representation of the object. This is used when the object is printed using the print() function or when the str() function is explicitly called on the object.

 

  • add: This method is called when the + operator is used on two objects. It is used to return the sum of the two objects.

 

  • len: This method is called when the len() function is used on an object. It is used to return the length of the object.

 

  • getitem: This method is called when the indexing operator ([]) is used on an object. It is used to return the element at the specified index of the object.

 

  • call: This method is called when an object is called like a function. It is used to implement the functionality of calling the object as a function

 

Additional Special Methods:

  • eq(self, other): This method is used to compare two objects for equality.
  • lt(self, other): This method is used to compare two objects for their relative size.
  • iter(self):This method is used to make an object iterable.

'Python(Eng. ver)' 카테고리의 다른 글

19. Python Module  (0) 2024.03.20
18. Python Error Handling  (0) 2024.03.19
16. Inheritance in Python  (0) 2024.03.19
15. Object-oriented programming and Class  (0) 2024.03.18
14. Callbacks and Lambdas in Python  (0) 2024.03.18