程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python language finishing

編輯:Python

目錄

  • 一、python
    • 1.python的基礎語法
      • 1.python的介紹
      • 2.python的注釋方法
        • 1.單行注釋:#
        • 2.多行注釋:三個單引號(’’’)或者三個雙引號(”””)
      • 3.python的數據類型
      • 4.面向對象
    • 2.python的構造函數
      • 1.pythonThe format of the constructor is :`__init__()`
      • 2.python查看變量內存地址:id
      • 3.顯式調用構造函數,會變成普通函數
      • 4.構造函數的返回值
      • 5.selfSave the eigenvalues ​​of different objects
      • 6.What is the difference between class variables and instance variables
      • 7.Dynamically add and modify variables
      • 8.__name__在Python中的作用
      • 9.Constructors can also be seen as special instance methods
    • 3.裝飾器
      • [email protected]:類方法
      • [email protected]:靜態方法
    • 3.公開,Protected and Private
    • 4.Subclasses pass values ​​to superclasses,需要使用super關鍵字
    • 5.閉包
    • 6.列表生成式
    • 7.生成器generator
    • 8.迭代器
    • 9.高階函數
      • 1)匿名函數
      • 2)map(__func, __iter1)
      • 3)reduce(__func, __iter1)
      • 4)filter(__function,__iterable)
      • 5)sorted(__iterable,key,reverse)

一、python

1.python的基礎語法

1.python的介紹

概述
Python 是一個高層次的結合了解釋性、編譯性、互動性和面向對象的腳本語言.

Python 的設計具有很強的可讀性,相比其他語言經常使用英文關鍵字,其他語言的一些標點符號,它具有比其他語言更有特色語法結構.

Python 是一種解釋型語言: 這意味著開發過程中沒有了編譯這個環節.類似於PHP和Perl語言.
Python 是交互式語言: 這意味著,你可以在一個Python提示符,直接互動執行寫你的程序.
Python 是面向對象語言: 這意味著Python支持面向對象的風格或代碼封裝在對象的編程技術.
Python 是初學者的語言:Python 對初級程序員而言,是一種偉大的語言,它支持廣泛的應用程序開發,從簡單的文字處理到 WWW 浏覽器再到游戲

2.python的注釋方法

1.單行注釋:#

Single-line comments are often preceded by #開頭
windows的快捷鍵是 Ctrl + /
實例:

# -太棒了
print ("hello world!"); #您好,世界

2.多行注釋:三個單引號(’’’)或者三個雙引號(”””)

注釋使用三個單引號(’’’)或者三個雙引號(”””)來標記,而實際上這是多行字符串的書寫方式,並不是Python本身提倡的多行注釋方法
實例:

'''
這是多行注釋,使用單引號.
這是多行注釋,使用單引號.
'''
"""
這是多行注釋,使用雙引號.
這是多行注釋,使用雙引號.
"""

3.python的數據類型

# int
a = 3
#float
a = 3.3
# str
a = 'str'
# bytes
a = b'4'
# complex
a = 2 + 3j
# bool
a = True
# None
a = None

Python語法比較松散,It is not mandatory to add at the end of the statement’;’,在定義變量時,There is no need to declare the data type of the variable,PythonThe data type is automatically given based on the assignment of the variable

If you are not sure about the type of a variable when you define it,可以使用None來進行賦值,The type at this time is alsoNone Type

4.面向對象

面向對象編程是一種封裝代碼的方法;代碼封裝就是隱藏實現功能的具體代碼,僅留給用戶使用的接口.
Python中也支持面向對象的三大特征:封裝、繼承、多態.

面向對象的相關術語
類:可以理解是一個模板,通過它來創建出無數個具體的實例;類是抽象一類事物的總稱,
對象:類時不可以直接使用的,需要通過類創建的實例才能使用,這個實例也就是對象.
屬性:類中的所有變量稱為屬性
方法:類中的所有函數通常叫做方法

The focus here is on classes and objects.
類的命名規則首字母最好大寫,可以采用駝峰寫法,例如:StudentName
python中的類也是通過用class來定義,並且他也可以下成“class student(object)”的方式來定義,括號內的是class所繼承的父類,如果不知道又想寫的話寫object就行.

2.python的構造函數

1.pythonThe format of the constructor is :__init__()

Want to have classes define different objects,We need constructors.Different constructors can assign different properties

#c9_1.cy
class Array1:
'''
The variables in the class are called
類變量
'''
data = 'ring01'
size = 1
# def __init__(self):
def __init__(self):
'''
構造函數,基本是通用的,包括php,java都有構造函數
'''
print('Array1')
def get_size(self):
print('get_size')

1.上述中class Array1The parent class behind is the default followerobject.class Array1(父類):
2.其中python當中的self如同javaand other languagesthis,Modifications are possible but not recommended.
3.pythonIt is automatically executed immediately after the class is instantiated

Automatically after instantiation eg

from c9_1 import Array1, Array2
arr = Array1()

結果

在運行pythonLater we found that it typed out automaticallyArray1,But we didn'tprintdisplay statement

2.python查看變量內存地址:id

If the instantiated objects are the same,The same here is just the internal variable value,The method is the same but in the computer but the memory address is different.

from c9_1 import Array1, Array2
arr = Array1()
arr1 = Array1()
arr2 = Array1()
#
print(id(arr), id(arr1), id(arr2))

結果:The three memory addresses are different

3.顯式調用構造函數,會變成普通函數

from c9_1 import Array1, Array2
arr = Array1()
arr.__init__()

結果:雖然這裡顯示了,But this constructor has become a normal function.【顯示兩次,One instantiation is displayed onceprintCalling the constructor shows】

Why is it printed twice
構造函數的特性:
1.The constructor is instantiated at the same time as the class,It is already running automatically
2.Can the constructor be called explicitly,明顯是可以的 But don't call it like this in programming

4.構造函數的返回值

from c9_1 import Array1, Array2
arr = Array1()
a = arr.__init__()
print(a)
print(type(a))

結果:

Two of the results Array1 已經解釋過了,但是為什麼有None的數據類型

解釋:
1.沒有return ?

2.The constructor should returnnone而不是int.

根本原因;本身是構造函數,Make it a normal function when you call it.而Ordinary functions need to return a value,構造函數不需要.但是我們沒有返回return
value所以函數默認返回None.

重點:構造函數不能,也不需要返回任何值

5.selfSave the eigenvalues ​​of different objects

定義實例方法時,需要有self這個參數.You don't need to be right when callingself傳參.

class Array2:
'''
The variables in the class are called
類變量
'''
data = 'ring02'
size = 2
def __init__(self, data, size):
'''
構造函數,基本是通用的,包括php,java都有構造函數
構造函數作用,初始化對象屬性
對象中的變量,Methods are properties
data,size都是實例變量
'''
data = data
size = size
def get_size(self):
print('get_size')
from c9_1 import Array1, Array2
arr2 = Array2([1,2,3,4,5], 5)
print(Array2.data)

結果:No value is displayed here

First we can see if the value is passed out,添加print查看

再次運行【print out the value,all outgoing values】

cause of the above;沒有使用selfSave the passed value
為此:

from c9_1 import Array2,Array3,Array4
arr3 = Array3([1,2,3,4], 4)
arr3.get_size()
arr3 = Array3([1,2,3,4,5,6], 6)
class Array3:
data = 'ring03'
size = 2
age = 11
def __init__(self, data1, size1):
self.data = data1
self.size = size1
"""
打印對象的屬性
"""
def get_size(self):
print('data is {}'.format(self.data))
print('size is %d' % self.size)
def get_data(self):
print(self.data)

結果:

Since we are instantiating the class 傳遞進來不同對象的特征值
那麼我們就需要Save the eigenvalues ​​of different objects
使用selfSave the properties of the object
self只和對象有關
誰調用了這個方法,selfWho is it about
self只和對象有關
和類無關

6.What is the difference between class variables and instance variables

from c9_1 import Array2,Array3,Array4
arr3 = Array3([1,2,3,4,5,6], 6)
print(arr3.__dict__)
print(arr3.size)
print(arr3.data)
class Array3:
data = 'ring03'
size = 2
age = 11
def __init__(self, data1, size1):
self.data = data1
self.size = size1
def get_size(self):
print('data is {}'.format(self.data))
print('size is %d' % self.size)
def get_data(self):
print(self.data)


dict:Displays all properties saved by the object

思考
在我們Array3defined in the array class,一個data和size是否合適?
我們Array3是一個類,這是一個模版
A big, empty thing
Define the concrete in the big and emptydata和size
這樣明顯是不合適的

7.Dynamically add and modify variables

class Array2:
'''
The variables in the class are called
類變量
'''
data = 'ring02'
size = 2
def __init__(self, data, size):
'''
構造函數,基本是通用的,包括php,java都有構造函數
構造函數作用,初始化對象屬性
對象中的變量,Methods are properties
data,size都是實例變量
'''
data = data
size = size
def get_size(self):
print('get_size')
from c9_1 import Array2,Array3,Array4
arr2 = Array3([1,2,3], 3)
# arr2對象動態添加lens變量
arr2.lens = 3
Array3.data = 'ring033'
print(arr2.__dict__)
print(Array3.__dict__)
print(arr2.data,arr2.size,arr2.lens, Array3.data)

結果:

Found that the object property itself is notlens的變量的,但是添加了
另外Array3.dataafter manually changing the value,The displayed value is also sent changed
上述中 data = 'ring02’與size = 2 ;The relationship between these two attributes and variables can be defined in the class,The object relationship is relatively close, it is best to be in the constructor.

補充
Think inside the object(Constructors also count)Accessing class variables is OK:print(self.class.data)

8.__name__在Python中的作用

pythonThere is usually one in the programif條件句

if __name__ == '__main__':

When there is thisifWhen in a module of a conditional sentence,This program will serve as the entry point of the program,name__會強制改為__main

When calling this module from another module,__name__The value is the filename of the module

9.Constructors can also be seen as special instance methods

Calling the constructor can be called directly when the class is instantiated,Instead call an instance method,是通過(對象.方法)use
arr.get_size

Think about printing inside the constructor
實例變量self.data與data
Are the results the same

解釋:
self.data與dataIs it really the same variable that is printed
Try putting the formal parametersdata改為data1,再次進行嘗試
self.dataInstance variables in the printed object dataAll that is printed is our formal parameters

3.裝飾器

lass Array5:
# Counts the sum of all elements in an array
"""
AOP思想
"""
sum = 1
# 類變量,實例變量
def __init__(self, data, size):
'''
self.__class__.sum
Array5.sum
:param data:
:param size:
'''
self.data = data
self.size = size
@classmethod
def class_arr(cls):
cls.sum += 1
# print(self.data)
print(cls.sum)
"""
裝飾器
"""
@staticmethod
def static_func1():
print('static')
def get_size(self):
# print(self.__class__.sum)
print('data is %s' % self.data)
print('size is %d' % self.size)

[email protected]:類方法

傳遞類:cls

from c9_1 import Array5
arr = Array5([1,2,3],3)
arr.get_size()
Array5.class_arr()

類方法
1.Manipulate class variables in instance methods
2.定義類方法(classmethod)
3.The role of class methods, as the name suggests, is to manipulate class variables 類方法中cls可以更改,但並不建議
4.Class methods are associated with our class itself,Instance methods are associated with our objects

各類方法

  1. __ new ()方法:是一種負責創建類實例的靜態方法,他不需要使用staticmethod裝飾器修飾,並且它優點於 init __ ()初始化方法被調用.
    2.
    repr __()方法:顯示屬性
  2. __ del __()方法:銷毀對象
  3. __ dir ()用法:列出地所有屬性名
    5.
    dict __()屬性:查看對象內部所有屬性名和屬性值組成的字典

[email protected]:靜態方法

And classes are less associated with objects,Basically a single method.【使用比較少】

3.公開,Protected and Private

protected:保護,可以被子類進行調用
private:私有方法,只可以被自己調用,子類也不行.
public:公有的

Protection and private distinction: Protected from being called by subclasses Private use only
__【Two underscores default to private properties】】

class Array6:
'''
The variables in the class are called
類變量
'''
data = 'ring02'
size = 2
def __init__(self, data, size):
'''
構造函數,基本是通用的,包括php,java都有構造函數
構造函數作用,初始化對象屬性
對象中的變量,Methods are properties
data,size都是實例變量
'''
self.data = data
self.size = size
self.__price = 0
# self.price = 0
# descI don't want others to make changes directly externally
def __modify_price(self, index):
if index < 0 or index > 100:
raise ValueError('range index error')
self.__price = index
print(self.__price)
def get_size(self):
print('data is %s' % self.data)
print('size is %d' % self.size)
def get_capacity(self):
print('capacity')

Accessing a private variable calls a function

from c9_1 import Array6
arr6 = Array6([1,2,3], 3)
print(arr6.__dict__)
print(Array6.__dict__)
arr6._Array6__price = 2
print(arr6.__dict__)

錯誤的修改方式
print(arr6.price)
arr6.get_size()
print(arr6.dict)
print(Array6.dict)
正確的修改方式
arr6.modify_price(2)
arr6.get_size()
私有方法,無法直接調用
print(arr6.dict)
print(Array6.dict)
arr6._Array6__modify_price(3)

4.Subclasses pass values ​​to superclasses,需要使用super關鍵字

class Student1(Person):
def __init__(self, organization, name, skill):
self.organization = organization
"""
Subclasses pass values ​​to superclasses,需要使用super關鍵字
"""
super().__init__(name, skill)
# def __init__(self, organization, name, skill):
# self.organization = organization
# super().__init__(name, skill)
def do_kill_monster(self):
pass
stu1 = Student1('英雄', 'king', 'Heart engine')
print(stu1.name)
print(stu1.skill)
print(stu1.organization)

If our subclass fully inherits the parent class 那麼子類存在沒任何意義
我們子類需要有一些不同於父類的變量,方法 這樣才能最大程度發揮好繼承作用

5.閉包

Structures that define functions and external environment variables are closures,Environment variables must be outside the function,And cannot be a global variable,And the return value of the outer function is the inner function.It remembers the state of the free variables

閉包 = 函數+環境變量(函數定義時候)
注意:Environment variables must be outside the defining function,而且不能是全局變量

def demo1():
a = 3
def demo2(x):
return a*x*x
return demo2
a = 10
d = demo1()

上述函數d = demo1(),其實是用demo1()函數,把demo2(x)賦給d

添加函數print(d.__closure__)閉包返回的是一個對象object,是將函數和環境變量都返回了

查看是否是閉包,還可以通過a.closure[index].cell_contents查看閉包中每個元組的值
添加函數print(d.__closure__[0].cell_contents)Environment variables for the returned closurea = 3

對d賦值,
The following format is a closure:There are external environment variables,自由變量,內部的函數,引用自由變量,Returns the inner function name

def demo1():
a = 3
def demo2(x):
return a*x*x
return demo2
a = 10
d = demo1()
print(d(2))

6.列表生成式

列表常用的方法
1.append()方法:用於在列表末尾添加型的對象—語法:list.appandd()
2.count()方法:用於統計某個元素在列表中出現的次數—語法:list.count()
3.extend()方法:用於在列表末尾異性追加另一個序列中的多個值—語法:list.extend(seq)
4.index()方法:用於從列表中找出某個值第一個匹配項的索引位置—語法:list.index(x[, start[, end]])-----x:查找的對象;start:開始位置,end:結束位置
5.pop()方法:用於移除列表中的一個元素,默認為列表中的最後一個元素,並且返回該元素的值—語法:list.pop([index=-1])
6.remove()方法:用於移除李彪中某個值的第一個匹配項----語法:list.remove(obj)
7.reverse()方法:將元素倒序排列

List comprehensions are essentially thatfor循環

aa = [i * i for i in range(1,5)]
print(aa)

遇見if else不能把if x % 2 == 0 else -xPut it in the back only in the front

fff = [x if x % 2 == 0 else -x for x in range(1,10)]
print(fff)

7.生成器generator

將列表[]改為()即可稱為生成器
只要把一個列表生成式的[]改成(),就創建了一個generator

generator保存的是算法 每次調用next(g),就計算出g的下一個元素的值,
直到計算到最後一個元素,沒有更多的元素時,拋出StopIteration的錯誤
一直用next調用【Step by step call】,一定不是一個好辦法,我們需要用for來調用 for可以將StopIteration處理 因為生成器也是一個可迭代對象,It does lazy matching

惰性匹配,The loop counts one at a time.This saves internal space when the loop starts to calculate

ll = (x * x for x in range(10))
print(next(ll))
print(next(ll))
print(next(ll))
print(next(ll))


The above expression can be changed tofor循環

ll = (x * x for x in range(10))
for i in ll:
print(i)


The benefits of using loops are,It will catch errors when the range is exceeded and will not report errors and output them directly.
報錯實例:

ll = (x * x for x in range(3))
print(next(ll))
print(next(ll))
print(next(ll))
print(next(ll)

yield命令:可以將正常數列變成生成器,他可以從中斷的位置繼續運行.

generator函數和普通函數的執行流程不同,普通函數遇到return語句或者最後一行函數語句就直接返回,但是generator函數再用next()調用執行的時候,遇到yield語句也會返回,但是再次執行的時候會從上此次返回的yield語句處執行.

對於yield的理解,can be understood as specialreturn關鍵字
當執行到yield i時,返回了i的值,And save the state of the function at this time,當使用nextwhen calling this generator function,It will continue the execution of the function from the time it just returned the value

8.迭代器

Iterate over objects and iteratorsnext
可迭代對象,可以被for循環的數據-----迭代器iter(),iter(),-------生成器 yield [] ()
可迭代對象:字符串、元組、列表、字典、set(在定義中最好放一個數組;set最主要的功能是可以去重)
生成器就是一種迭代器,可以被next調用並不斷返回下一個值的對象稱為迭代器:iterator.
優先級:generator生成器 > itertor > iterable

9.高階函數

1)匿名函數

使用lambda關鍵字修飾的簡單函數

lambda x,y: x>y?x:y
def add_demo(x,y):
return x + y
def print_str(x):
return x
f = lambda x, y : x + y
print(f(2,3))

2)map(__func, __iter1)

__func函數:Pass in the function value and function name
__iter1函數:處理
mapPass in the first parameter to accept a function,The second parameter is an iterable object,結果返回一個迭代器.
即:使用__iter1迭代器執行__func函數

3)reduce(__func, __iter1)

與mapSimilar is used__iter1迭代器執行__func函數
不同與map:將上一次計算的結果作為下一次計算的參數

4)filter(__function,__iterable)

用__function函數過濾,__iterable中的元素

5)sorted(__iterable,key,reverse)

依據key的值排序__iterable中的元素,reverse決定是否逆序


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved