Python中一切皆为对象

作者: 是九歌呀 | 来源:发表于2018-05-06 01:16 被阅读17次

众所周知,面向对象语言的特点即为“万物皆为对象”,其中以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')

相关文章

  • Python3 & 类方法,实例方法,静态方法详解

    类对象和实例对象 类:Python中一切皆为对象,对象是抽象的,Python中的对象用类来表示。而在实示使用时,通...

  • python面向对象(一)从C语言开始

    一切皆为对象。在java中对象是数据和方法的结合,而python中关于对象的定义是: 凡能当作参数传递,就是对象 ...

  • 面向对象分析

    Python3 面向对象编程 所谓对象,一切事物皆为对象,在编程中对象实际就是数据与相关行为对集合。 对象与类之间...

  • Python中一切皆为对象

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

  • 2章 对象与变量

    本章大纲 对象 变量 变量操作 对象 一切(万物)皆为对象 常见对象-数字 整数 ​ python 语言里 一...

  • Python语法特点总结

    1. Python对象模型 Python中一切皆为对象。 对象拥有三个特性:id、类型和值。 类把数据与功能绑定在...

  • Python函数传递参数:对象引用

    一、变量与对象 Python 中一切皆为对象,数字是对象,列表是对象,函数也是对象,任何东西都是对象。 变量是对象...

  • python中一切皆对象

    python中一切皆对象 python中的一切皆对象更加彻底在python中的一切皆对象比Java中的一切皆对象更...

  • Python 函数中,参数是传值,还是传引用?

    1. 变量与对象: Python 中一切皆为对象。数字是对象,列表是对象,函数也是对象,任何东西都是对象。 而变量...

  • Python中的“垃圾”是怎么回收的?

    前言 对于python来说,一切皆为对象,所有的变量赋值都遵循着对象引用机制。程序在运行的时候,需要在内存中开辟出...

网友评论

    本文标题:Python中一切皆为对象

    本文链接:https://www.haomeiwen.com/subject/swdyrftx.html