• Python学习笔记


    推荐书籍

    来自:http://tieba.baidu.com/p/2076545024 

    微博:@python爱好者

    A Byte of Python中文教程.pdf python简明教程中文.pdf---适合有c,C++,java,C#经验者,快速入门,用在工作上。http://www.kuqin.com/abyteofpython_cn/ch11s05.html

    Introduction to Programming Using Python.pdf------适合没有任何编程经验者,华人写的编程书。
    Think Python How to Think Like a Computer Scientist---在线免费书.
    Learn Python The Hard Way 2nd Edition.pdf------适合没有任何编程经验者,喜欢通过做题学习的同学。
    OReilly.Learning.Python.3rd.Edition.Oct.2007.pdf------适合没有任何编程经验者,喜欢讲的详细的同学。
    Python 核心编程 第二版------适合有编程经验者,全面掌握python知识。
     


    数据结构

    在Python中有三种内建的数据结构——列表、元组和字典

    列表

    你可以在列表中添加 任何种类的对象 包括数甚至其他列表,一些方法举例:

     1 shoplist = ['apple', 'mango', 'carrot', 'banana']  # 声明
     2 
     3 len(shoplist)
     4 
     5 for item in shoplist:
     6     print item
     7 
     8 shoplist.append('rice')
     9 
    10 shoplist.sort()
    11 
    12 olditem = shoplist[0] 
    13 del shoplist[0]  #del的是shoplist[0],不是olditem(下一句还要用)
    14 print 'I bought the', olditem

    sort方法对列表排序。这个方法影响列表本身,而不是返回一个修改后的列表——这与字符串工作的方法不同。这就是我们所说的列表是 可变的 而字符串是 不可变的 。

    PS:print 结束加上逗号会去掉自带的换行

    元组

    元组和列表类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。常用于打印。疑问:不能排序?

    空的元组myempty = ()。一个包含项目2的元组的时候,你应该指明singleton = (2 , )

    1 #!/usr/bin/python
    2 # Filename: print_tuple.py
    3 
    4 age = 22
    5 name = 'Swaroop'
    6 
    7 print '%s is %d years old' % (name, age)
    8 print 'Why is %s playing with that python?' % name

    字典

    (名字)和(详细情况)联系在一起。键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。

    只能使用不可变的对象(比如字符串)来作为字典的键。基本说来就是,你应该只使用简单的对象(python里对象指一切哦~不单指class的实例)作为键。

    键值对在字典中:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

    字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

    字典是dict类的实例/对象。

     1 #!/usr/bin/python
     2 # Filename: using_dict.py
     3 
     4 # 'ab' is short for 'a'ddress'b'ook
     5 
     6 ab = {       'Swaroop'   : 'swaroopch@byteofpython.info',
     7              'Larry'     : 'larry@wall.org',
     8              'Matsumoto' : 'matz@ruby-lang.org',
     9              'Spammer'   : 'spammer@hotmail.com'
    10      }
    11 
    12 print "Swaroop's address is %s" % ab['Swaroop']
    13 
    14 # Adding a key/value pair
    15 ab['Guido'] = 'guido@python.org'
    16 
    17 # Deleting a key/value pair
    18 del ab['Spammer']
    19 
    20 print '
    There are %d contacts in the address-book
    ' % len(ab)
    21 for name, address in ab.items():
    22     print 'Contact %s at %s' % (name, address)
    23 
    24 if 'Guido' in ab: # OR ab.has_key('Guido')
    25     print "
    Guido's address is %s" % ab['Guido']

    del语句删除键/值对。只需要指明字典和用索引操作符指明要删除的键,然后把它们传递给del语句就,无需知道那个键所对应的值。

    使用字典的items方法,来使用字典中的每个键/值对(如果是列表则是for i in ab)这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。我们抓取这个对,然后分别赋给for..in循环中的变量nameaddress然后在for-块中打印这些值。

    可以使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法。你可以使用help(dict)来查看dict类的完整方法列表。

    关键字参数与字典。如果换一个角度看待你在函数中使用的关键字参数的话,你已经使用了字典了!只需想一下——你在函数定义的参数列表中使用的键/值对。当你在函数中使用变量的时候,它只不过是使用一个字典的键(这在编译器设计的术语中被称作 符号表 )。这几句 看得稀里糊涂的,囧

     序列

    列表、元组和字符串都是序列。序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串。

    • 索引操作符:从序列中抓取一个特定项目(可以为负)
    1 shoplist = ['apple', 'mango', 'carrot', 'banana']
    2 
    3 # Indexing or 'Subscription' operation
    4 print 'Item 0 is', shoplist[0] 
    5 print 'Item -1 is', shoplist[-1]
    6 #输出
    7 #Item 0 is apple
    8 #Item -1 is banana
    • 切片操作符:获取序列的一个切片,即一部分序列([num1:num2],num可选,冒号必须;从num1开始,从num2前一个结束,即前闭后开)
     1 # Slicing on a list,接上面
     2 print 'Item 1 to 3 is', shoplist[1:3] 
     3 print 'Item 2 to end is', shoplist[2:]
     4 print 'Item 1 to -1 is', shoplist[1:-1]
     5 print 'Item start to end is', shoplist[:]
     6 #输出
     7 #Item 1 to 3 is ['mango', 'carrot']
     8 #Item 2 to end is ['carrot', 'banana']
     9 #Item 1 to -1 is ['mango', 'carrot']
    10 #Item start to end is ['apple', 'mango', 'carrot', 'banana']
    11 
    12 # Slicing on a string
    13 name = 'swaroop'
    14 print 'characters 1 to 3 is', name[1:3]
    15 #输出
    16 #characters 1 to 3 is wa

    对象和参考(此处对象也是指各种哦~)

    变量名指向你计算机中存储那个对象的内,而不是对象本身。这被称作名称到对象的绑定

     1 #!/usr/bin/python
     2 # Filename: reference.py
     3 
     4 print 'Simple Assignment'
     5 shoplist = ['apple', 'mango', 'carrot', 'banana']
     6 mylist = shoplist # mylist is just another name pointing to the same object!
     7 
     8 del shoplist[0]
     9 
    10 print 'shoplist is', shoplist
    11 print 'mylist is', mylist
    12 # notice that both shoplist and mylist both print the same list without
    13 # the 'apple' confirming that they point to the same object
    14 #输出
    15 #Simple Assignment
    16 #shoplist is ['mango', 'carrot', 'banana']
    17 #mylist is ['mango', 'carrot', 'banana']
    18 
    19 
    20 print 'Copy by making a full slice'
    21 mylist = shoplist[:] # make a copy by doing a full slice
    22 del mylist[0] # remove first item
    23 
    24 print 'shoplist is', shoplist
    25 print 'mylist is', mylist
    26 # notice that now the two lists are different
    27 #输出
    28 #Copy by making a full slice
    29 #shoplist is ['mango', 'carrot', 'banana']
    30 #mylist is ['carrot', 'banana']

    想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么必须使用切片操作符来取得拷贝

    如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。

    字符串的一些方法(help(str))

    字符串也是对象,都是str类的对象,也有方法,如:

     1 name = 'Swaroop' # This is a string object 
     2 
     3 if name.startswith('Swa'):
     4     print 'Yes, the string starts with "Swa"'
     5 
     6 if 'a' in name:
     7     print 'Yes, it contains the string "a"'
     8 
     9 if name.find('war') != -1:
    10     print 'Yes, it contains the string "war"'
    11 
    12 delimiter = '_*_'
    13 mylist = ['Brazil', 'Russia', 'India', 'China']
    14 print delimiter.join(mylist)  #输出Brazil_*_Russia_*_India_*_China

    类和对象

    两者关系的理解:创建一个新类型,而对象这个类的实例(instance) 。类似于有一个int类型的变量,而存储整数的变量是int类的实例(对象)。

    属性

    属于一个对象或类的变量被称为。域有两种类型——属于每个实例/类的对象 或 属于类本身。它们分别被称为实例变量类变量

    属于类的函数来实现具体功能,这样的函数被称为类的方法

    (这些术语帮助我们把它们与孤立的函数和变量区分开来。域和方法可以合称为类的属性。)

    self

    类的方法与普通的函数只有一个特别的区别——必须有一个额外的第一个参数名称self

    原理举例:假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)

    __init__方法

    __init__方法在类的一个对象被建立时,马上运行。可以用来对对象做一些初始化(initialize) 。

     1 #!/usr/bin/python
     2 # Filename: class_init.py
     3 
     4 class Person:
     5     def __init__(self, name):
     6         self.name = name
     7     def sayHi(self):
     8         print 'Hello, my name is', self.name
     9 
    10 p = Person('Swaroop')  # 注意这里
    11 p.sayHi()

    没有专门调用__init__方法,只是在创建新实例的时候,把参数传递给__init__方法。这是这种方法的重要之处。

     (例子中这样就能够在方法中使用self.name域:sayHi()

    类与对象的数据部分

    它们只是与类和对象的名称空间 绑定 的普通变量,即这些名称只在这些类与对象的前提下有效。

    两种域:

    • 类的变量 :由一个类的所有对象(实例)共享。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。
    • 对象的变量 :由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,不是共享的。在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。
     1 #!/usr/bin/python
     2 # Filename: objvar.py
     3 
     4 class Person:
     5     '''Represents a person.'''
     6     population = 0
     7 
     8     def __init__(self, name):
     9         '''Initializes the person's data.'''
    10         self.name = name
    11         print '(Initializing %s)' % self.name
    12 
    13         # When this person is created, he/she
    14         # adds to the population
    15         Person.population += 1
    16 
    17     def __del__(self):
    18         '''I am dying.'''
    19         print '%s says bye.' % self.name
    20 
    21         Person.population -= 1
    22 
    23         if Person.population == 0:
    24             print 'I am the last one.'
    25         else:
    26             print 'There are still %d people left.' % Person.population
    27 
    28     def sayHi(self):
    29         '''Greeting by the person.
    30 
    31         Really, that's all it does.'''
    32         print 'Hi, my name is %s.' % self.name
    33 
    34     def howMany(self):
    35         '''Prints the current population.'''
    36         if Person.population == 1:
    37             print 'I am the only person here.'
    38         else:
    39             print 'We have %d persons here.' % Person.population
    40 
    41 swaroop = Person('Swaroop')
    42 swaroop.sayHi()
    43 swaroop.howMany()
    44 
    45 kalam = Person('Abdul Kalam')
    46 kalam.sayHi()
    47 kalam.howMany()
    48 
    49 swaroop.sayHi()
    50 swaroop.howMany()

    输出

     1 $ python objvar.py
     2 (Initializing Swaroop)
     3 Hi, my name is Swaroop.
     4 I am the only person here.
     5 (Initializing Abdul Kalam)
     6 Hi, my name is Abdul Kalam.
     7 We have 2 persons here.
     8 Hi, my name is Swaroop.
     9 We have 2 persons here.
    10 Abdul Kalam says bye.
    11 There are still 1 people left.
    12 Swaroop says bye.
    13 I am the last one.

    这里,population属于Person类,因此是一个类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。

    __init__方法用一个名字来初始化Person实例。在这个方法中,我们让population增加1,这是因为我们增加了一个人。

    self.name的值根据每个对象指定,这表明了它作为对象的变量的本质。

    后面这些有点不相关,先粘贴着吧~

    记住,你能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。

    在这个程序中,我们还看到docstring对于类和方法同样有用。我们可以在运行时使用Person.__doc__Person.sayHi.__doc__来分别访问类与方法的文档字符串。

    就如同__init__方法一样,还有一个特殊的方法__del__,它在对象消逝的时候被调用。对象消逝即对象不再被使用,它所占用的内存将返回给系统作它用。在这个方法里面,我们只是简单地把Person.population1

    当对象不再被使用时,__del__方法运行,但是很难保证这个方法究竟在 什么时候 运行。如果你想要指明它的运行,你就得使用del语句,就如同我们在以前的例子中使用的那样。

    继承

    面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过 继承 机制。继承完全可以理解成类之间的 类型和子类型 关系。

    假设你想要写一个程序来记录学校之中的教师和学生情况。他们有一些共同属性,比如姓名、年龄和地址。他们也有专有的属性,比如教师的薪水、课程和假期,学生的成绩和学费。你可以为教师和学生建立两个独立的类来处理它们,但是这样做的话,如果要增加一个新的共有属性,就意味着要在这两个独立的类中都增加这个属性。这很快就会显得不实用。一个比较好的方法是创建一个共同的类称为SchoolMember然后让教师和学生的类 继承 这个共同的类。即它们都是这个类型(类)的子类型,然后我们再为这些子类型添加专有的属性。使用这种方法有很多优点。如果我们增加/改变了SchoolMember中的任何功能,它会自动地反映到子类型之中。例如,你要为教师和学生都增加一个新的身份证域,那么你只需简单地把它加到SchoolMember类中。然而,在一个子类型之中做的改动不会影响到别的子类型

    另外一个优点是你可以把教师和学生对象都作为SchoolMember对象来使用,这在某些场合特别有用,比如统计学校成员的人数。一个子类型在任何需要父类型的场合可以被替换成父类型,即对象可以被视作是父类的实例,这种现象被称为多态现象

    另外,我们会发现在 重用 父类的代码的时候,我们无需在不同的类中重复它。而如果我们使用独立的类的话,我们就不得不这么做了。

    在上述的场合中,SchoolMember类被称为 基本类 或 超类 。而TeacherStudent类被称为 导出类 或 子类 

     1 #!/usr/bin/python
     2 # Filename: inherit.py
     3 
     4 class SchoolMember:
     5     '''Represents any school member.'''
     6     def __init__(self, name, age):
     7         self.name = name
     8         self.age = age
     9         print '(Initialized SchoolMember: %s)' % self.name
    10 
    11     def tell(self):
    12         '''Tell my details.'''
    13         print 'Name:"%s" Age:"%s"' % (self.name, self.age),
    14 
    15 class Teacher(SchoolMember):
    16     '''Represents a teacher.'''
    17     def __init__(self, name, age, salary):
    18         SchoolMember.__init__(self, name, age)
    19         self.salary = salary
    20         print '(Initialized Teacher: %s)' % self.name
    21 
    22     def tell(self):
    23         SchoolMember.tell(self)
    24         print 'Salary: "%d"' % self.salary
    25 
    26 t = Teacher('Mrs. Shrividya', 40, 30000)

    输入输出

    文件(help(file))

    举例几个方法:

     1 f = file('poem.txt', 'w') # open for 'w'riting
     2 f.write(poem) # write text to file
     3 f.close() # close the file
     4 
     5 f = file('poem.txt')
     6 # if no mode is specified, 'r'ead mode is assumed by default
     7 while True:
     8     line = f.readline()
     9     if len(line) == 0: # Zero length indicates EOF
    10         break
    11     print line,
    12     # Notice comma to avoid automatic newline added by Python
    13 f.close() # close the file

    对文件的读写能力依赖于你在打开文件时指定的模式。可使用file类的readreadlinewrite等方法来恰当地读写文件。

    ________你所记的,都是假的。
  • 相关阅读:
    题解 CF700E Cool Slogans
    题解 LOJ2065 「SDOI2016」模式字符串
    以guest账号无密码访问设置
    共享
    计算机的C$共享在哪里
    网卡工作原理
    iperf网络测试
    Jmeter安装与使用(压测)
    压测工具使用(vegeta)
    Alertmanager 安装(k8s报警)
  • 原文地址:https://www.cnblogs.com/pudding-ai/p/4512410.html
Copyright © 2020-2023  润新知