Python中一切皆为对象

众所周知,面向对象语言的特点即为“万物皆为对象”,其中以Java开发尤为突出。那么在python中,这个 一切 是怎么表现出来的呢?

一切皆为对象(函数和类也是对象)

在Python中,函数和类也是对象。他们体现在以下几个方面

1. 可以赋值给一个变量

# 函数可以被赋值给变量
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()

通过以上代码可以发现使用新的变量名即可调用函数

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

# 定义集合对象
obj_list = []
# 添加方法与类到几个中
obj_list.append(hello)
obj_list.append(Person)

for item in obj_list:
    print(item())

输出结果:


6275828-5c425755be9e428b.png
输出结果.png

注:
以上输出结果中hello world以及init为print函数输出语句。None为函数返回值,无返回值时即为None值

3.可以作为参数传递给函数

# 可以作为参数传递给函数

# 输出类型
def print_type(item):
    print(type(item))

for item in obj_list:
    print_type(item)

输出结果:


6275828-1ceef8805ee11875.png
输出结果.png

4.可以当做函数返回值

# 可以当做函数返回值
def decorator_func():
    print('调用decorator_func函数')
    return hello

my_func = decorator_func()
my_func('python')
6275828-2413da951bd166e0.png
输出结果

注:
此即为Python中装饰器实现原理

All Code

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

# 函数可以被赋值给变量
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())

## 可以作为参数传递给函数
def print_type(item):
    print(type(item))

# for item in obj_list:
#     print_type(item)


# 可以当做函数返回值
def decorator_func():
    print('调用decorator_func函数')
    return hello

my_func = decorator_func()
my_func('python')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值