__________     __ __     __  _______    ________
  / ____/ __ \   / // /    / / / /  _/ |  / / ____/
 / / __/ / / /  / // /_   / /_/ // / | | / / __/
/ /_/ / /_/ /  /__  __/  / __  // /  | |/ / /___
\____/\____/     /_/    /_/ /_/___/  |___/_____/

 --- A GOPHER-LIKE INTERFACE FOR HIVE BLOCKCHAIN ---

Python: Magic Methods

BY: @neophyte | CREATED: March 22, 2018, 5:15 a.m. | VOTES: 1 | PAYOUT: $0.00 | [ VOTE ]

 Introduction

They are special methods with fixed names. These methods have double underscores at the beginning and the end of their name. Magic methods are sometimes called dunder methods.

The magic in magic methods is that we don't have to explicitly call it. When an instance of a class is created the magic methods are automatically called behind the screen.

call method

It enables us to write classes whose instances behave like functions. Both functions and the instances of such classes are called callable. A callable object behaves like a function. An instance can be a callable object if the class has call method. 
class A:
   def init(self):
       print("An instance of A was initialized")
   def call(self, args, *kwargs):
       print("Arguments are:", args, kwargs)

x = A()
print("now calling the instance:")
x(3, 4, x=11, y=10)
print("Let's call it again:")
x(3, 4, x=11, y=10)

Output:
An instance of A was initialized
now calling the instance:
Arguments are: (3, 4) {'x': 11, 'y': 10}
Let's call it again:
Arguments are: (3, 4) {'x': 11, 'y': 10}

To check the list of all magic methods in a class, print the following command
class MyClass:     pass
dir(Myclass)

For more info and examples please refer to the following link: https://www.python-course.eu/python3_magic_methods.php

TAGS: [ #python ] [ #call-method ]

Replies

NO REPLIES FOUND.

[ BACK TO TRENDING ] [ BACK TO MENU ]
CMD>