欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python一切皆对象_Python中一切皆为对象

发布时间:2025/3/15 python 42 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python一切皆对象_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())

输出结果:

输出结果.png

注:

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

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

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

# 输出类型

def print_type(item):

print(type(item))

for item in obj_list:

print_type(item)

输出结果:

输出结果.png

4.可以当做函数返回值

# 可以当做函数返回值

def decorator_func():

print('调用decorator_func函数')

return hello

my_func = decorator_func()

my_func('python')

输出结果

注:

此即为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')

总结

以上是生活随笔为你收集整理的python一切皆对象_Python中一切皆为对象的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。