Python 高级编程和异步IO并发编程 --02_1 一切皆对象

Python中,Class/函数/代码/模块都是对象。

0. 新建函数

a. New Project

b. New Python Package

c. 在package中,New Python File

1. 函数赋值给变量

def ask(name="LiLei"):
    print(name)

my_func = ask  # 将函数当作对象,赋值给变量
my_func("Hanmeimei")
C:\Users\Amber\PycharmProjects\test0\venv\Scripts\python.exe C:/Users/Amber/PycharmProjects/test0/Chapter01/all_is_object.py
Hanmeimei

类赋值给变量

def ask(name="LiLei"):
    print(name)

class Person:
    def __init__(self):
        print("LiLei")

#my_func = ask  # 将函数当作对象,赋值给变量
#my_func("Hanmeimei")

my_class = Person  # 将类当作对象,赋值给变量
my_class()   # 类的实例化
C:\Users\Amber\PycharmProjects\test0\venv\Scripts\python.exe C:/Users/Amber/PycharmProjects/test0/Chapter01/all_is_object.py
LiLei

2. 添加到集合对象中

def ask(name="LiLei-1"):
    print(name)

class Person:
    def __init__(self):
        print("LiLei-2")

obj_list = []
obj_list.append(ask)
obj_list.append(Person)
for item in obj_list:
    print(item())
C:\Users\Amber\PycharmProjects\test0\venv\Scripts\python.exe C:/Users/Amber/PycharmProjects/test0/Chapter01/all_is_object.py
LiLei-1     # 此处调用ask函数,输出LiLei-1
None        # ask函数被调用完后,由于ask函数没有定义返回值,因此默认返回None
LiLei-2     # 此处调用Person类,执行输出LiLei-2
<__main__.Person object at 0x000001C761BE6988>    # __init__函数本身不返回实例,对实例化时,返回的是类的对象 

Process finished with exit code 0

3. 作为函数的返回值

def ask(name="LiLei-1"):
    print(name)

class Person:
    def __init__(self):
        print("LiLei-2")

def decorator_func():  # 返回函数,是python装饰器的原理
    print("Dec start")
    return ask

my_ask = decorator_func()
my_ask("tom")
C:\Users\Amber\PycharmProjects\test0\venv\Scripts\python.exe C:/Users/Amber/PycharmProjects/test0/Chapter01/all_is_object.py
Dec start   # 调用decorator_func函数,打印Dec start
tom  # 返回ask函数,调用的参数是tom
发布了224 篇原创文章 · 获赞 59 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/f2157120/article/details/104829114