Hướng dẫn __call__ trong python

Ví dụ của bài viết này mô tả việc sử dụng Python __ call__ trong call__ và chia sẻ nó với bạn để bạn tham khảo. Phương pháp cụ thể như sau:

Hãy xem mã ví dụ sau:

#call.py A class Đang tải.
class Next:
List = <>

def __init__(self,low,high) :
for Num in range(low,high) :
self.List.append(Num ** 2)

def __call__(self,Nu):
return self.List

Nếu vậy:

b = Next(1,7)
print b.List
print b(2)

Vì vậy, phản hồi là bình thường:

[1, 4, 9, 16, 25, 36]
9

Nhưng nếu bạn sử dụng nó như thế này:

b = Next
b(1,7)
print b.List
print b(2)
$python ./call.py
[1, 4, 9, 16, 25, 36]
Traceback (most recent call last):
File "cal.py", line 17, in
print b(2)
TypeError: __init__() takes exactly 3 arguments (2 given)

__init__ là chức năng khởi tạo, thực thi khi tạo một thể hiện.

__ call__ là lệnh gọi của mô phỏng (), cần được áp dụng trên ví dụ, vì vậy trường hợp này tự nhiên đã thực hiện __ init__.

Ví dụ cuối cùng bạn đã nêu ra:

b = Next

Điều này không phải là để tạo các ví dụ, mà là để cung cấp class cho một biến. Do đó, hoạt động sử dụng B là hoạt động của lớp Next, vì vậy nó thực sự là:

Next(1,7)
print Next.List
print Next(2)

Tôi hy vọng rằng thiết kế chương trình Python mô tả bài viết này sẽ giúp mọi người.


View Discussion

Nội dung chính

  • Difference between __init__() VS __call__()
  • What is __ call __ function in Python?
  • What are __ methods called in Python?
  • What is the __ str __ method used for?
  • What does __ class __ mean in Python?

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

    object() is shorthand for object.__call__()

    Example 1:

    class Example:

        def __init__(self):

            print("Instance Created")

        def __call__(self):

            print("Instance is called via special method")

    e = Example()

    e()

    Output :

    Instance Created
    Instance is called via special method
    

    Example 2:

    class Product:

        def __init__(self):

            print("Instance Created")

        def __call__(self, a, b):

            print(a * b)

    ans = Product()

    ans(10, 20)

    Output :

    Instance Created
    200
    

    View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Dunder or magic methods in Python are the methods having two prefixes and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc. In this article, we are going to see the difference between two such methods.

    Note: For more information, refer to Dunder or magic methods in Python

    __init__()

    This Python method is similar to a constructor in any other programming language. A constructor is a definition with the same name as the class and is invoked automatically when the object of that class is defined. A constructor initializes all the required entities of the program to make it more reliable.
    Similar to this definition __init__() works as a Python constructor it is invoked automatically when an object of the class is defined. It initializes the required members with default values provided. It can also be invoked with the values provided during the time of declaration of the object of the class.

    EXAMPLE:

    class A:

        def __init__(self, x):

            print("inside __init__()")

            self.y = x

        def __str__(self):

            print("inside __str__()")

            print("value of y:", str(self.y))

    a = A(3)

    a.__str__()

    b = A(10)

    b.__str__()

    OUTPUT:

    inside __init__()
    inside __str__()
    ('value of y:', '3')
    inside __init__()
    inside __str__()
    ('value of y:', '10')
    

    __call__()

    Before getting into application of __call__() we need to understand what a callable object is.
    A callable object is one which can be called like a function.
    In Python, __call__() is used to resolve the code associated with a callable object. Any object can be converted to a callable object just by writing it in a function call format. An object of that kind invokes the __call__() method and executes the code associated with it. This doesn’t make the object not to work like a normal one. The object can be used as a normal is used.
    One thing to keep in mind is the object is itself used as a function, so syntax should be right.

    EXAMPLE:

    class A:

        def __init__(self, x):

            print("inside __init__()")

            self.y = x

        def __str__(self):

            print("inside __str__()")

            print("value of y:", str(self.y))

        def __call__(self):

            res = 0

            print("inside __call__()")

            print("adding 2 to the value of y")

            res = self.y + 2

            return res

    a = A(3)

    a.__str__()

    r = a()

    print(r)

    b = A(10)

    b.__str__()

    r = b()

    print(r)

    OUTPUT:

    inside __init__()
    inside __str__()
    ('value of y:', '3')
    inside __call__()
    adding 2 to the value of y
    5
    inside __init__()
    inside __str__()
    ('value of y:', '10')
    inside __call__()
    adding 2 to the value of y
    12

    Difference between __init__() VS __call__()

    __init__()__call__()
    Same as a constructor, it initializes the values It is used for a direct call using the object
    It is invoked automatically when an object is declared It is invoked automatically by a callable
    Called by an regular object Called by a callable object
    Example:
    a=A(3) #statement 1
    a() #statement 2
    __init__() is called by statement 1
    Example:
    a=A(3) #statement 1
    a() #statement 2
    __call__() is called by statement 2

    What is __ call __ function in Python?

    The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

    What are __ methods called in Python?

    Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods.

    What is the __ str __ method used for?

    Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

    What does __ class __ mean in Python?

    __class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: b. __class__ # Output: After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .