Python中一切皆為對象

眾所周知,面向?qū)ο笳Z言的特點即為“萬物皆為對象”,其中以Java開發(fā)尤為突出。那么在python中,這個 一切 是怎么表現(xiàn)出來的呢?

一切皆為對象(函數(shù)和類也是對象)

在Python中,函數(shù)和類也是對象。他們體現(xiàn)在以下幾個方面

1. 可以賦值給一個變量

# 函數(shù)可以被賦值給變量
def hello(name='world'):
    print('hello ' + name)

my_func = hello
my_func('python')
# 類可以被賦值給變量
class Person:
    def __init__(self):
        print('__init__')

my_class = Person
my_class()

通過以上代碼可以發(fā)現(xiàn)使用新的變量名即可調(diào)用函數(shù)

2.可以添加到集合對象中

# 定義集合對象
obj_list = []
# 添加方法與類到幾個中
obj_list.append(hello)
obj_list.append(Person)

for item in obj_list:
    print(item())

輸出結(jié)果:


輸出結(jié)果.png

注:
以上輸出結(jié)果中hello world以及init為print函數(shù)輸出語句。None為函數(shù)返回值,無返回值時即為None值

3.可以作為參數(shù)傳遞給函數(shù)

# 可以作為參數(shù)傳遞給函數(shù)

# 輸出類型
def print_type(item):
    print(type(item))

for item in obj_list:
    print_type(item)

輸出結(jié)果:


輸出結(jié)果.png

4.可以當(dāng)做函數(shù)返回值

# 可以當(dāng)做函數(shù)返回值
def decorator_func():
    print('調(diào)用decorator_func函數(shù)')
    return hello

my_func = decorator_func()
my_func('python')
輸出結(jié)果

注:
此即為Python中裝飾器實現(xiàn)原理

All Code

# /bin/python3
# -*- coding:utf-8 -*-
"""
Python中一切皆為對象
"""

# 函數(shù)可以被賦值給變量
def hello(name='world'):
    print('hello ' + name)

# my_func = hello
# my_func('python')

# 類可以被賦值給變量
class Person:
    def __init__(self):
        print('__init__')

# my_class = Person
# my_class()

# 可以添加到集合對象中

# 定義集合對象
obj_list = []
# 添加方法與類到幾個中
obj_list.append(hello)
obj_list.append(Person)

# for item in obj_list:
#     print(item())

## 可以作為參數(shù)傳遞給函數(shù)
def print_type(item):
    print(type(item))

# for item in obj_list:
#     print_type(item)


# 可以當(dāng)做函數(shù)返回值
def decorator_func():
    print('調(diào)用decorator_func函數(shù)')
    return hello

my_func = decorator_func()
my_func('python')
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容