python Notes

python Chinese encoding

# -*- coding:UTF-8 -*-

python identifier

In Python, identified by letters, numbers, underscores.
Identifiers beginning with an underscore have a special significance. _Foo begin single underline represent can not directly access the class attributes, accessed through the classes provided from xxx import * can not be introduced.
In the private members of class representatives __foo double underlined beginning to foo __ __ Representative Python double underline in particular the beginning and end of the specific identification method, such as the init __ __ constructor () represent the class.

python variable type

Variable assignment does not require the type of statement in python, for example:

name = "dali"

Standard data types
Python five standard data types:
Numbers (numbers)
String (String)
List (list)
Tuple (tuple)
the Dictionary (dictionary)
(s dictionary element is accessed by key)

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
 
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
 
 
print dict['one']          # 输出键为'one' 的值
print dict[2]              # 输出键为 2 的值
print tinydict             # 输出完整的字典
print tinydict.keys()      # 输出所有键
print tinydict.values()    # 输出所有值

Operators python

python arithmetic operators
x ** exponentiation y - y x to the power return
// take divisible - returns the integer part of the quotient, rounded down
python logical operators
and
or
Not

python list

Delete list elements

list = ['Google', 'Runoob', 1997, 2000]
 
print ("原始列表 : ", list)
del list[2]
print ("删除第三个元素 : ", list)

python list of functions & methods

#函数
lenlist#列表元素个数
maxlist#返回列表元素最大值
minlist#返回列表元素最小值
list(seq)#将元组转换为列表
#方法
list.append(obj)#在列表末尾添加新的对象
list.count(obj)#统计某个元素在列表中出现的次数
list.extend(seq)#在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj)#从列表中找出某个值第一个匹配项的索引位置
list.insert(index,obj)#将对象插入列表
list.pop([index=-1])#移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj)#移除列表中的某个值的第一个匹配项
list.reverse()#反向列表中的元素
list.sort(key=None,reverse=Flase)#对原列表进行排序
list.clear()#清空列表
list.copy()#复制列表

python tuple

Python is similar to a list of tuples, except that the elements of the tuple can not be modified.
Tuples use parentheses, square brackets list.
Tuple create very simple, only need to add elements in parentheses and separated by commas can be.

tup1 = () #创建空元组

python dictionary

Another variable is the dictionary container model, and can store any type of object.
Each dictionary key (key => value) of the colon (:) divided, (,) between each pair separated by commas, including whole dictionary in curly braces ({}) in the following format:

d = {key1 : value1, key2 : value2 }

Methods included in the dictionary

radiansdict.clear()#删除字典内所有元素
radiansdict.copy()#返回一个字典的浅复制
radiansdict.get(key,default=None)#返回指定键的值,如果值不在字典中返回default值
key in dict #如果键在字典中就返回true,否则返回false
radiansdict.items()#以列表返回可遍历的(键,值)元组数组
radiansdict.keys()#返回一个迭代器,可以使用list()来转换为列表
radiansdict.setdefault(key,default=None)#和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2)#把字典dict2的键/值对更新到dict里
radiansdict.values()#返回一个迭代器,可以使用 list() 来转换为列表

python collection

Collection (set) is an unordered sequence of elements will not be repeated.
Braces {} may be used or a set () function creates a set of note: Create an empty set must be set () instead of {}, {} as is used to create an empty dictionary.
The basic set of operations

#添加元素
s.add(x)
s.update(x)
#移除元素
s.remove(x)
s.discard(x)
#计算集合元素个数
len(s)
#清空集合
s.clear()

end keyword

Keyword end may be used to output to the same line, or add different characters output at the end of the following examples:

 print(b, end=',')

Creating an iterator

#把一个类作为一个迭代器使用需要在类中实现两个方法 __iter__() 与 __next__() 。
#如果你已经了解的面向对象编程,就知道类都有一个构造函数,Python 的构造函数为 __init__(), 它会在对象初始化的时候执行。
#__iter__() 方法返回一个特殊的迭代器对象, 这个迭代器对象实现了 __next__() 方法并通过 StopIteration 异常标识迭代的完成。
#__next__() 方法(Python 2 里是 next())会返回下一个迭代器对象。
class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    x = self.a
    self.a += 1
    return x
 
myclass = MyNumbers()
myiter = iter(myclass)

Builder

In Python, using a function generator is referred to as yield (generator).
The difference is that with an ordinary function, the generator is a return iterator function can only be used to iterate operation, more simply understood generator is a iterator.
During the call generator is running, each encounter yield function pauses and save all of the current operating information, the return value of yield, and the next execution of the next () continue to operate from its current position method.
Calling a generator function, it returns an iterator object.

import sys
 
def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
 
while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()
 
 #运行结果
 0 1 1 2 3 5 8 13 21 34 55

function

def 函数名(参数列表):
	函数体
#匿名函数
#python使用lambda创建匿名函数
lambda [arg1 [,arg2,.....argn]]:expression
sum = lambda arg1, arg2: arg1 + arg2

Module

___ name_ __ properties of
a module is first introduced into another program which runs the main program. If we want when the module is introduced, a block module is not performed, we can attribute to __name__ The block only executed in the runtime module itself.

if __name__ == '__main__':
   print('程序自身在运行')
else:
   print('我来自另一模块')
'''
说明: 每个模块都有一个__name__属性,当其值是'__main__'时,表明该模块自身在运行,否则是被引入。
说明:__name__ 与 __main__ 底下是双下划线, _ _ 是这样去掉中间的那个空格。
'''

Object-oriented python3

Examples of variables: the class declaration, the attribute is represented by a variable, the variable is called an instance variable, instance variable is a self-modified variables.

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i)   # 输出结果:3.0 -4.5

Method class
within the class used to define a method def keyword, different function definitions and the general class method must contain parameters self, and is the first parameter, representative of the Self are instances of classes.

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
# 实例化类
p = people('runoob',10,30)
p.speak()
#runoob 说: 我 10 岁。

inherit

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))
 
 
 
s = student('ken',10,60,3)
s.speak()
Published an original article · won praise 0 · Views 13

Guess you like

Origin blog.csdn.net/qq_42545310/article/details/104859330