python一切皆对象_Python中一切皆为对象
眾所周知,面向?qū)ο笳Z(yǔ)言的特點(diǎn)即為“萬(wàn)物皆為對(duì)象”,其中以Java開(kāi)發(fā)尤為突出。那么在python中,這個(gè) 一切 是怎么表現(xiàn)出來(lái)的呢?
一切皆為對(duì)象(函數(shù)和類(lèi)也是對(duì)象)
在Python中,函數(shù)和類(lèi)也是對(duì)象。他們體現(xiàn)在以下幾個(gè)方面
1. 可以賦值給一個(gè)變量
# 函數(shù)可以被賦值給變量
def hello(name='world'):
print('hello ' + name)
my_func = hello
my_func('python')
# 類(lèi)可以被賦值給變量
class Person:
def __init__(self):
print('__init__')
my_class = Person
my_class()
通過(guò)以上代碼可以發(fā)現(xiàn)使用新的變量名即可調(diào)用函數(shù)
2.可以添加到集合對(duì)象中
# 定義集合對(duì)象
obj_list = []
# 添加方法與類(lèi)到幾個(gè)中
obj_list.append(hello)
obj_list.append(Person)
for item in obj_list:
print(item())
輸出結(jié)果:
輸出結(jié)果.png
注:
以上輸出結(jié)果中hello world以及init為print函數(shù)輸出語(yǔ)句。None為函數(shù)返回值,無(wú)返回值時(shí)即為None值
3.可以作為參數(shù)傳遞給函數(shù)
# 可以作為參數(shù)傳遞給函數(shù)
# 輸出類(lèi)型
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中裝飾器實(shí)現(xiàn)原理
All Code
# /bin/python3
# -*- coding:utf-8 -*-
"""
Python中一切皆為對(duì)象
"""
# 函數(shù)可以被賦值給變量
def hello(name='world'):
print('hello ' + name)
# my_func = hello
# my_func('python')
# 類(lèi)可以被賦值給變量
class Person:
def __init__(self):
print('__init__')
# my_class = Person
# my_class()
# 可以添加到集合對(duì)象中
# 定義集合對(duì)象
obj_list = []
# 添加方法與類(lèi)到幾個(gè)中
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')
總結(jié)
以上是生活随笔為你收集整理的python一切皆对象_Python中一切皆为对象的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机技能大赛试题及答案,全国中职计算机
- 下一篇: html打开时按钮自动触发事件,html