Python magic method__ call__ Research

Time:2022-5-26

__ call__ Method interpretation

The official definition is to turn the instantiated class into a callable object, which is difficult to understand. Personally, if the class is defined__ call__ Method, then a callable feature is extended to this class, which can be called like a function. For example, a = class name () a (parameter) is equivalent to a__ call__ (parameter)

class apple(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __call__(self,x,y):
        self.x = x
        self.y = y

    def get(self,x,y):
        self.x = x
        self.y = y

a = apple(1,2)
print(a.x)
print(a.y)

a(3,4)
print(a.x)
print(a.y)

a.get(5,6)
print(a.x)
print(a.y)

A (4,5) is equal to a__ call__ (4,5)

If not defined__ call__ () method, but using a (4,5) directly will report an error

Traceback (most recent call last):
  File "D:/flaskLearn/study/magicMethod/wuhf_a.py", line 22, in 
    a(4,5)
TypeError: 'apple' object is not callable

The above code returns the result

1
2
3
4
5
6

__ call__ Method application

What are callable objects

The callable (obj) method will return whether the parameter can be called. If it can be called, it will return true. Otherwise, it will return false

  • Variable cannot be called
  • Function can be called
  • Class can be called
  • The instantiated class cannot be called
  • Added__ call__ Method can be called
uu = 23
Print ("can the variable UU be called?", callable(uu))
def orange():
    pass
Print ("can orange be called?", callable(orange))
class peach(object):
    def __init__(self):
        pass
upeach = peach()
Print ("can class peach be called?", callable(peach))
Print ("can class instance upeach be called?", callable(upeach))
fapple = apple(1,2)
Print ("can class instance fapple be called?", callable(fapple))

Return results

Can the variable UU be called? False
Can the function orange be called? True
Can class peach be called? True
Can class instance upeach be called? False
Can class instance fapple be called? True

How to judge the attributes and methods in an instance

The instantiated class contains attributes and methods. How can we judge whether a key is an attribute or a method?

The hasattr (obj, attribute) function can check whether an attribute or method is stored in a class instance, but it cannot determine whether it is an attribute or a method. We can use__ call__ To judge,

Instance property does not exist__ call__

Instance method has__ call__

print(hasattr(a,'x'))
print(hasattr(a,'get'))
print(hasattr(a,'set'))
print(hasattr(a,'__call__'))

if hasattr(a,'x'):
    Is the method "print", hasattr(a.x,'__call__'))
if hasattr(a,'get'):
    Print ("is get a method?", hasattr(a.get,'__call__'))

Return results

True
True
False
True
Is x the method? False
Is get a method? True