简体   繁体   中英

Is id a python builtin function?

Would you please look at code below,

def getCrewListAll(self):
    """
    Set to crew list to all available crew
    """
    crew = getIdNumbers()
    return map(lambda cr: cr.id, crew)

What is the meaning of cr.id here, is id a builtin python function or?

In your example, the reference to cr.id is not a function call. Its accessing a member attribute of the cr variable, which is a placeholder for whatever the crew objects are.

id is the name of a builtin function , yes. But there is no way to know if its being used under the hood in these objects without seeing the actual class definitions.

As an example... if this were, say, a django application, model instances have id member attributes that give you the database id of that record. Its part of the design of the class for that framework.

Even though I am assuming its an attribute... for all we know it could also be a computed property which is similar to a method call that acts like an attribute. It could be doing more logic that it seems when looking at your example.

Lastly, since the cr.id could be anything, it could even be a method and the map is returning a lis of callables: cr.id()

cr.id isn't a builtin function (unless you've assigned it to be...), it's a normal member of the cr object there.

id(cr) would be an invocation of that builtin and would return the identity of cr .

I think the real problem here is that you don't understand the code you have posted. In this context you need to understand map and lambda .

map is a function which applies a function to each element of a list and returns this as a list:

>>> def func(a):
...   return a * 2
...
>>> map(func, [1,2,3])
[2, 4, 6]

lambda can be seen as a shortcut to create functions. The above could be written with lambda :

>>> func = lambda a: a * 2
>>> map(func, [1,2,3])
[2, 4, 6]

So what your code map(lambda cr: cr.id, crew) is doing: It returns a list of the id attribute from each of the objects in the list crew .

The problem is that this code is actually not pretty good. You can write the same function with a list comprehension , which is much more intuitive:

def getCrewListAll(self):
    return [cr.id for cr in getIdNumbers()]

there is a built in id function but may or may not be related to this, depending on the implementation of that object, either way id here is a member/property of that object.

If you are curious to see what kind of members/fields that object has you can do dir(crew[0]) assuming its retuning at least one, and if its properly document you can also do this help(crew[0].id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM