模块、类和对象

1.字典,记住键值对的概念,记住从键值对

mystuff = {'apple':"I am apples"}
print mystuff['apple']

2.模块

'''
	模块
	1.模块是包含函数和变量的文件
	2.模块这个文件可以被导入
	3.可以使用.操作符访问模块中的函数和变量
'''

#模块代码示例
#以下是一个模块,名字叫mystuff.py

# this goes in mustuff.py
def apple():
	print("I am a apple!")	
# this is just a variable 
tangerine = 'Living reflection of a dream.'

#接下来可以使用import来调用这个模块,并且访问模块中的函数以及变量

import mystuff
mystuff.apple()
print(mystuff.tangerine)

#执行上面的代码输出结果如下
[root@localhost module]# python module_test.py 
I am a apple!
Living reflection of a dream.

'''
	总结以及对比
	1.模块好比字典的升级版,类似于键值对风格的容器
	2.通过键获取值,对于字典来说,键是一个字符串,获取值的语法是["key"];
	3.对于模块来说,键是函数或者变量的名称,通过.key语法来获取值。
	4.以上,并没有其他的区别
'''

3.类和对象 类也是一个容器,我们可以把函数和数据放入这个容器中,并且通过"."操作符来访问他们。

class Mystuff(object):
	"""docstring for Mystuff"""
	def __init__(self):
		#添加属性,初始化对象
		self.tangerine = "for the win"
	def apple(self):
		print("I am classy apples!")
#创建对象---类的实例化(instantiate)
thing = Mystuff()
thing.apple()
print(thing.tangerine)

#执行代码的输出结果

[root@localhost class]# python mystuff.py 
I am classy apples!
for the win