python function object

First-class objects ( English : First-class object) in computer science can be created and passed as parameters to other functions or into a middle finger in the implementation of variable entity. The process entity becomes a first-class objects is called "object oriented" (Reification).

What is first-class objects:

  • Created at runtime

  • Elements can be assigned to variables or data structures

  • It can be passed as a parameter to the function

  • You can return the result as a function of

 

1. As a function of the object, with three common object model attributes: id, type, and value.

Copy the code
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def foo():
    print('from foo')
foo()

print(id(foo))
print(type(foo))
print(foo)
Copy the code

Export

from foo
4406808360
<class 'function'>
<function foo at 0x106aa8f28>

2. The function can be referenced, that function can be assigned to a variable

This function can also be assigned to more variables, the only change is a reference to the function object count increasing, the final nature of these variables are pointing to the same function object.

Copy the code
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def foo():
    print('from foo')

foo()
func=foo    #引用,赋值
print(foo)
print(func)
func()
Copy the code

Export

from foo
<function foo at 0x10eed8f28>
<function foo at 0x10eed8f28>
from foo

 

3. The function may be passed as a parameter

Copy the code
def foo():
    print('from foo')

def bar(func):
    print(func)
    func()

bar(foo)
Copy the code

Export

<function foo at 0x1047eff28>
from foo

 

4 can function as a return value

Function takes one or more functions as an input or output function (return) value is a function of the time, we call such functions as higher-order functions

Copy the code
def foo():
    print('from foo')

def bar(func):
    return func     

f=bar(foo)

print(f)

f()
Copy the code

Export

<function foo at 0x107f29f28>
from foo

 

The function of the elements can be used as container type

Container object (list, dict, set, etc.) can be stored in any object, including integer, string, functions can also be stored in the container object

Copy the code
def foo():
    print('from foo')
dic={'func':foo}

foo()

print(dic['func'])

dic['func']()
Copy the code

Export

from foo
<function foo at 0x10997ef28>
from foo

 

6. The function can also be nested

Nested function definitions

Copy the code
def f1():

    def f2():
        print('from f2')
        def f3():
            print('from f3')
        f3()
    f2()


f1()
Copy the code

Export

from f2
from f3

 

application

Copy the code
def get(text):
    def clean(t):   #2
        return t[1:]
    new_text = clean(text)  #1
    return len(new_text)

print(get('python'))
Copy the code

Export

5

 

Higher-order functions

Function as a function of the parameter or function return value is called the higher order function

 

Anonymous function

Anonymous function name suggests is no name, it creates the lambda keyword, that is a turnkey, saving time to create a function, also called a lambda expression


fruits = ['strawberry','apple','cherry','banana',' pineapple'] list = sorted(fruits,key=lambda x:x[-1]) print(list) # ['banana', 'apple', ' pineapple', 'strawberry', 'cherry'] 

The above sorted () function in order to sort the last character of the fruit, there is no practical significance, but using a lambda expression example.

 

Callables

Functions are objects, the function name in parentheses is calling this function, then other objects can also become like a function call can be bracketed it

It is possible, only we need to implement special methods in a class call


class Fruit(): def __init__(self,name): self.name = name def __call__(self, *args, **kwargs): print(self.name+' was called') apple = Fruit('apple') apple() # apple was called 

The method may further add any call parameter, and a function.

Can for an object is invoked by Callable () function to determine


print(callable(apple)) # True
print(callable(Fruit)) # True

You can call returns True. Here we find Fruit can also be invoked, because the class is also an object, Fruit is also an instance of the class that created it also implements the method call, will not elaborate here.

 

Reference: https://www.cnblogs.com/smallmars/p/6936871.html

  https://www.cnblogs.com/sfencs-hcy/p/10454125.html

Guess you like

Origin www.cnblogs.com/wisir/p/11072116.html