Python中一切皆对象
一、python中一切皆对象
函数和类也是对象,属于python的一等公民。
1、赋值给一个变量;
(1) 函数:
# 示例一:
def ask(name="大麻花"):
print(name)
my_func = ask
my_func()
运行结果:
大麻花
# 示例二:
def ask(name="大麻花"):
print(name)
my_func = ask
my_func("米线")
运行结果:
米线
(2) 类:
class Person():
def __init__(self):
print("大麻花")
my_class = Person
my_class()
运行结果:
大麻花
2、可以添加到集合对象中;
# 函数没有return返回值
def ask(name="米线"):
print(name)
class Person():
def __init__(self):
print("大麻花")
obj_list = []
obj_list.append(ask)
obj_list.append(Person)
for item in obj_list:
print(item())
运行结果:
米线
None
大麻花
<__main__.Person object at 0x7f54acb93748>
# 函数有return返回值
def ask(name="米线"):
print(name)
return name
class Person():
def __init__(self):
print("大麻花")
obj_list = []
obj_list.append(ask)
obj_list.append(Person)
for item in obj_list:
print(item())
运行结果:
米线
米线
大麻花
<__main__.Person object at 0x7f17e21e2748>
3、可以作为参数传递给函数;
def ask(name="麻花"):
print(name)
return name
def decorator_func(func):
result = func
print("ask函数返回结果:%s" %result)
print("dec start")
my_ask = decorator_func(ask("米线"))
my_ask
运行结果:
米线
ask函数返回结果:米线
dec start
4、可以当做函数的返回值。
def ask(name="麻花"):
print(name)
return name
def decorator_func():
print("dec start")
return ask
my_ask = decorator_func()
my_ask("米线")
运行结果:
dec start
米线
二、type、object和class之间的关系
1、映射关系:
(1) type --> int --> 1
a = 1
print(type(a))
print(type(int))
运行结果:
<class 'int'>
<class 'type'>
(2) type --> class --> obj
b = "abc"
print(type(b))
print(type(str))
运行结果:
<class 'str'>
<class 'type'>
(3) object是顶层基类
class Student:
pass
class MyStudent(Student):
pass
stu = Student()
print(type(stu))
print(type(Student))
print(int.__bases__)
print(str.__bases__)
print(Student.__bases__)
print(MyStudent.__bases__)
print(object.__bases__)
运行结果:
<class '__main__.Student'>
<class 'type'>
(<class 'object'>,)
(<class 'object'>,)
(<class 'object'>,)
(<class '__main__.Student'>,)
()
(4) type也是一个类,同时type也是一个对象
print(type.__bases__)
print(type(object))
运行结果:
(<class 'object'>,)
<class 'type'>
2、关系图:
三、python中的内置类型
1、对象的三个特征:
(1) 身份:通过 id() 函数获取对象的身份信息。
>>> a = 1
>>> id(a)
94028039139424
>>> a = {}
>>> id(a)
139908772465160
(2) 类型:通过 type() 函数获取对象的类型。
>>> a = 1
>>> type(a)
<class 'int'>
>>> a = {}
>>> type(a)
<class 'dict'>
(3) 值:
>>> a = 1
>>> a
1
>>> a = {}
>>> a
{}
2、None(全局只有一个)
>>> a = None
>>> b = None
>>> id(a) == id(b)
True
>>> a == b
True
>>> type(a) == type(b)
True
3、数值:int、float、complex(复数)、bool
4、迭代类型:
5、序列类型:list、bytes(二进制序列)、bytearray(二进制序列)、memoryview(二进制序列)、range、tuple、str、array
6、映射(dict):
7、集合:set、frozenset
8、上下文管理类型(with):
9、其他:模块类型、class和实例、函数类型、方法类型、代码类型、object对象、type类型、ellipsis类型、notimplemented类型