【Python基础】lpthw

  一、 模块(module)

  模块中包含一些函数和变量,在其他程序中使用该模块的内容时,需要先将模块import进去,再使用.操作符获取函数或变量,如

1 # This goes in mystuff.py
2 def apple():
3     print("This is an apple.")
4 
5 pear = "This is a pear."
1 import mystuff as ms
2 ms.apple()
3 
4 print(ms.pear)

  输出为

This is an apple.
This is a pear.

  二、 类(class)

  类与模块的比较:使用类可以重复创建很多东西出来(后面会称之为实例化),且这些创建出来的东西之间互不干涉。而对于模块来说,一次导入之后,整个程序就只有这么一份内容,更改会比较麻烦。

  一个典型的类的例子:

1 class Mystuff(object):
2 
3     def __init__(self):
4         self.tangerine = "And now a thousand years between"
5 
6     def apple(self):
7         print("I AM CLASSY APPLES!")

  注意体会其中的object、__init__和self。

  三、 对象(object)

  对象是类的实例化,类的实例化方法就是像函数一样调用一个类。

1 thing = Mystuff()    # 类的实例化
2 thing.apple()
3 print(thing.tangerine)

  详解类的实例化过程:

  1. python查找Mystuff()并知道了它是你定义过的一个类。
  2. python创建一个新的空对象,里面包含了你在该类中用def指定的所有函数。
  3. 检查用户是否在类中创建了__init__函数,如果有,则调用这个函数,从而对新创建的空对象实现初始化
  4. 在Mystuff的__init__函数中,有一个叫self的函数,这就是python为你创建的空对象,你可以对它进行类似模块、字典等的操作,为它设置一些变量。
  5. 此处将self.tangerine设置成了一段歌词,这样就初始化了该对象。
  6. 最后python将这个新建的对象赋给一个叫thing的变量,以供后面的使用。

  四、获取某样东西里包含的东西

  字典、模块和类的使用方法对比:

 1 # dict style
 2 mystuff['apple']
 3 
 4 # module style
 5 # import mystuff
 6 mystuff.apple()
 7 
 8 # class style
 9 thing = mystuff()
10 thing.apple()

  五、第一个类的例子

 1 class Song(object):
 2 
 3     def __init__(self,lyrics):
 4         self.lyrics = lyrics
 5 
 6     def sing_me_a_song(self):
 7         for line in self.lyrics:
 8             print(line)
 9 
10 happy_bday = Song(["Happy birthday to ~ you ~",
11                     "Happy birthday to ~ you ~",
12                     "Happy birthday to ~ you ~~",
13                     "Happy birthday to you ~~~"])
14 
15 bulls_on_parade = Song(["They rally around the family",
16                         "With pockets full of shells"])
17 
18 happy_bday.sing_me_a_song()
19 
20 bulls_on_parade.sing_me_a_song()

  输出

Happy birthday to ~ you ~
Happy birthday to ~ you ~
Happy birthday to ~ you ~~
Happy birthday to you ~~~
They rally around the family
With pockets full of shells
  •   为什么创建__init__等函数时要多加一个self变量?

  因为如果不添加self,lyrics = “blahblahblah”这样的代码就会有歧义,它指的既可能是实例的lyrics属性,也可能是一个叫lyrics的局部变量。有了self.lyrics = "blahblahblah",就清楚的知道这指的是实例的属性lyrics。

原文地址:https://www.cnblogs.com/cry-star/p/10669127.html