What does this variable mean?

1

I'm messing with python and pycuda, studying codes and etc and I came across the following question: What's happening exactly on the second line? service will receive some attributes, in the first line, and until then everything okay. However in the second line service is a function ?? What role does the service play there?

service = getattr(entity, event["name"])
service(event["data"], event["tx"], event["txId"])

In pycuda I noticed something similar:

func = mod.get_function("doublify")
func(a_gpu, block=(4,4,1))

In the above code I had the impression that "func" will take on the role of "doublify" (a CUDA code snippet) and after receiving some arguments. In the first example of "service", this became obscure to me.

    
asked by anonymous 21.05.2018 / 21:29

1 answer

4

It turns out that methods are also attributes of an object. In this case, event["name"] will have the name of a method of the entity object and when it does:

service = getattr(entity, event["name"])

The service object will be a reference to the method. For example, if event['"name"] had the value start , the equivalent code would be:

service = entity.start

The simplest way to do this assignment dynamically is through the function getattr . So in the second line:

service(event["data"], event["tx"], event["txId"])

It's nothing more than calling the method passing three values as parameters.

As for the second example, it is difficult to say with certainty, as it depends on the definition of the object mod and method get_function , but everything indicates that it is the same situation: returns the reference to a function and then makes its call .

See an example:

class Foo:
    def hello(self, name):
        print(f'Hello {name}')

foo = Foo()
func = getattr(foo, 'hello')

# print(type(func))  # <class 'method'>

func('world')  # Hello world
    
21.05.2018 / 21:38