Python入门100个实例(19)——对象与值

从本实例学到什么

  1. 对象与值的关系
  2. id函数得到对象的编号

实例程序代码

#例2-4-5  对象与值
#Python程序中,每一个值都用一个对象来存储。
hi = "Hi, everyone."   #这一语句会生成字符串对象。
print("字符串对象的类型:", type(hi))
n = 123  #生成整数对象
print("整数对象的类型:", type(n))
f = 5.6  #生成浮点数对象
print("浮点数对象的类型:", type(f))

#id()函数返回对象的ID
print("字符串对象的ID:", id(hi))
print("整数对象的ID:", id(n))
print("浮点数对象的ID:", id(f))

print("n+f=", n+f)
print("id(n+f):", id(n + f))  #生成一个没名字的整数对象,存有128.6这个值。

hi_u = hi.upper()   #生成一个包含全大写字母的字符串对象。hi_u是这个对象的名字。
print("hi字符串变成大写:", hi_u)
print("id(hi.upper()):", id(hi_u))

运行例2-4-5,输出以下内容:

字符串对象的类型: < class ‘str’ >
整数对象的类型: < class ‘int’ >
浮点数对象的类型: < class ‘float’ >
字符串对象的ID: 7866800
整数对象的ID: 1784615184
浮点数对象的ID: 4497912
n+f= 128.6
id(n+f): 4497888
hi字符串变成大写: HI, EVERYONE.
id(hi.upper()): 7868016

type函数和id函数

type函数返回对象的类型。比如,例2-4-5第4行中,type(hi)返回hi变量引用的对象的类型。具体的返回值是:< class ‘str’ >,意味着对象的类型是str,即字符串类型。

id函数返回对象的编号(即ID)。Python程序运行后,会为生成的每一个对象分配全局唯一的编号。这就像学校为每一个学生分配唯一的学号一样。比如,例2-5-4第11行中,id(hi)返回hi变量引用的对象的ID。

对象与值的关系

Python程序中,任何一个值都存储为一个对象。字面量也存储为一个对象。
上面运行例2-4-5的输出内容可见,”Hi, everyone.”这个值存储为ID是7866800的对象;123这个整数值存储为ID是1784615184的对象;5.6这个值存储为ID是4497912的对象。

每个对象都有一个身份标识、一个类型、一个值以及若干属性。属性分数据属性和方法属性。数据属性的一个例子有学生对象的年龄,又一个例子是学生对象的性别。方法属性的例子如字符串对象的upper(), title()等方法。

前面讲过,变量是值的名字。一个值总被一个对象所包含,因此变量是对象的名字。再说一次,变量是对象的名字。

想要更多地了解对象与值的关系,参阅《[译]Python 语言参考-3.1. 对象、值和类型》

dir函数列出对象的属性

在上面给出例2-4-5的尾部增加以下代码:

#dir()函数返回对象的属性
print("字符串对象的属性:")
print(dir(hi))
#print("整数对象的属性:")
#print(dir(n))
#print("浮点数对象的属性:")
#print(dir(f))

增加的代码将输出以下内容:

字符串对象的属性:
[’ _ add _ ‘, ’ _ class _ ‘, ’ _ contains _ ‘, ’ _ delattr _ ‘, ’ _ dir _ ‘, ’ _ doc _ ‘, ’ _ eq _ ‘, ’ _ format _ ‘, ’ _ ge _ ‘, ’ _ getattribute _ ‘, ’ _ getitem _ ‘, ’ _ getnewargs _ ‘, ’ _ gt _ ‘, ’ _ hash _ ‘, ’ _ init _ ‘, ’ _ iter _ ‘, ’ _ le _ ‘, ’ _ len _ ‘, ’ _ lt _ ‘, ’ _ mod _ ‘, ’ _ mul _ ‘, ’ _ ne _ ‘, ’ _ new _ ‘, ’ _ reduce _ ‘, ’ _ reduce_ex _ ‘, ’ _ repr _ ‘, ’ _ rmod _ ‘, ’ _ rmul _ ‘, ’ _ setattr _ ‘, ’ _ sizeof _ ‘, ’ _ str _ ‘, ’ _ subclasshook _ ‘, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]

dir函数输出对象拥有的属性。dir(hi)输出字符串对象拥有的属性。你能在上述字符串对象的属性清单中找到upper和title等方法属性。

小结

  1. Python中,一个值是以对象的形式存在的。
  2. 每一个对象有一个ID,一个类型、一个值和若干属性。
  3. 变量是对象的名字。
  4. id函数返回对象的ID。
  5. dir函数返回对象的属性清单。

猜你喜欢

转载自blog.csdn.net/yedouble/article/details/81224506