字典
mystuff = {'apple': "I AM APPLE!"}
调用
print(mystuff['apple'])
模块
def apple():
print("I AM APPLE!")
#另一个变量
tangerine = "Living reflection of a dream"
保存为 mystuff.py 文件
调用
import mystuff
mystuff.apple()
#打印 "I AM APPLE!"
print(mystuff.tangerine)
总之,调用模块里面的变量和函数都需要使用"模块名字+.+函数(或者变量)" 进行操作。
类
class MyStuff(object):
def __init__(self): # 类里面的变量这样定义???? init
self.tangerine = " And now a thousand years between"
def apple(self):
print("I AM CLASSY APPLES!")
thing = MyStuff() # 调用类,实例化类
thing.apple() # 调用 类 里面的函数 apple
print(thing.tangerine) # 调用类里面的变量 tangerine
理解:类的调用(实例化)就是模块的引入,然后使用模块的方式调用类里面的函数和变量
类2
class Song(object):
def __init__(self,lyrics):
# 这里声明self 具有一个 lyrics 的特性
self.lyrics = lyrics
def sing_me_a_song(self): # 调用self
for line in self.lyrics:
print(line)
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"]) # 列表歌词. 实例化类 或者 模块的引入
bulls_on_parade = Song(["They rally around the family",
"With pocket full of shells"]) # 列表歌词 实例化类 或者 模块的引入
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()