Modules, classes, and objects
1. Dictionary, remember the concept of key-value pairs, remember from key-value pairs
mystuff = {‘apple‘:"I am apples"}print mystuff[‘apple‘]
2. Module
‘‘‘ 模块 1.模块是包含函数和变量的文件 2.模块这个文件可以被导入 3.可以使用.操作符访问模块中的函数和变量‘‘‘#模块代码示例#以下是一个模块,名字叫mystuff.py# this goes in mustuff.pydef apple(): print("I am a apple!") # this is just a variable tangerine = ‘Living reflection of a dream.‘#接下来可以使用import来调用这个模块,并且访问模块中的函数以及变量import mystuffmystuff.apple()print(mystuff.tangerine)#执行上面的代码输出结果如下[[email protected] module]# python module_test.py I am a apple!Living reflection of a dream.‘‘‘ 总结以及对比 1.模块好比字典的升级版,类似于键值对风格的容器 2.通过键获取值,对于字典来说,键是一个字符串,获取值的语法是["key"]; 3.对于模块来说,键是函数或者变量的名称,通过.key语法来获取值。 4.以上,并没有其他的区别‘‘‘
3. Classes and objects
Class is also a container, we can put functions and data into this container, and through the "." Operators to access them.
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)#执行代码的输出结果[[email protected] class]# python mystuff.py I am classy apples!for the win
Modules, classes, and objects (Python learning notes)