What does this variable mean?

Asked

Viewed 55 times

1

I’m dealing with python and pycuda, studying codes and so on and came across the following question: What exactly is happening in 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 a role the service is playing there ?

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

In pycuda I noticed something similar too:

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

In the code above I had the impression that "func" will perform the role of "doublify" (an excerpt of CUDA code) and then receives some arguments. In the first example, of "service", it became obscure for me.

1 answer

4


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

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

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

service = entity.start

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

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

It is nothing more than the call to the method passing three values as parameters.

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

Take 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.