Python basic knowledge learning
Aug 17, 2024 am 07:42 AMPython is an interpreted, object-oriented, high-level programming language with dynamic data types. Python was invented by Guido van Rossum at the end of 1989, and the first public release was released in 1991. Like the Perl language, Python source code also follows the GPL (GNU General Public License) agreement.
Function is defined through the def keyword and looks like
python def function (arg1,arg2,...): ... fuction(1,2,...) #call function
DocStringsdocstrings
DocStrings Docstrings are an important tool for interpreting documentation programs.
``` python def function(): ''' say something here! ''' pass ... print function.__doc__ #調用doc ```
*DocStrings documentation string usage convention. Its first line starts with a capital letter to briefly describe the function, the second line is blank, and the third line is a specific description of the function*
Python module (Module) is a Python file, ending with .py, containing Python object definitions and Python statements.
Modules allow you to organize your Python code snippets logically. Assigning related code into a module can make your code more usable and easier to understand. Modules can define functions, classes and variables, and modules can also contain executable code. Here’s how to load it:
import method (all imported)
import modules
Note: A module will only be imported once, no matter how many times you execute the import. This prevents imported modules from being executed over and over again.
from ... import method (partial introduction)
Python's from statement lets you import a specified section from a module into the current namespace. The syntax is as follows:
from modname import name1[, name2[, ... nameN]]
from ... import* statement
Importing all content in the module is not recommended.
Python module search path
When you import a module, the Python parser searches for module locations in the following order:
Current directory
If not in the current directory, Python searches every directory under the shell variable PYTHONPATH.
If neither is found, Python will look at the default path. Under UNIX, the default path is generally /usr/local/lib/python/. The module search path is stored in the system module's sys.path variable. The variables contain the current directory, PYTHONPATH and the default directory determined by the installation process.
The function is a sorted list of strings, the content of which is the name defined in a module.
The returned list contains all modules, variables and functions defined in a module.
The special string variable __name__ points to the name of the module, and __file__ points to the name of the import file of the module.
Depending on where it is called, the globals() and locals() functions can be used to return names in the global and local namespaces.
If locals() is called inside a function, all names accessible within the function are returned. If globals() is called inside a function, all global names accessible within the function are returned. The return type of both functions is a dictionary. So the names can be extracted using the keys() function.
A package is a hierarchical file directory structure, which defines a Python application environment composed of modules and sub-packages, and sub-packages under sub-packages. Simply put, a package is a folder, but the _init_.py file must exist in the folder, and the content of this file can be empty. _init_.py is used to identify the current folder as a package.
Commonly used modules
系統(tǒng)相關的信息模塊: import sys sys.argv 是一個 list,包含所有的命令行參數(shù). sys.stdout sys.stdin sys.stderr 分別表示標準輸入輸出,錯誤輸出的文件對象. sys.stdin.readline() 從標準輸入讀一行 sys.stdout.write("a") 屏幕輸出a sys.exit(exit_code) 退出程序 sys.modules 是一個dictionary,表示系統(tǒng)中所有可用的module sys.platform 得到運行的操作系統(tǒng)環(huán)境 sys.path 是一個list,指明所有查找module,package的路徑.
操作系統(tǒng)相關的調用和操作: import os os.environ 一個dictionary 包含環(huán)境變量的映射關系 os.environ["HOME"] 可以得到環(huán)境變量HOME的值 os.chdir(dir) 改變當前目錄 os.chdir('d:\outlook') 注意windows下用到轉義 os.getcwd() 得到當前目錄 os.getegid() 得到有效組id os.getgid() 得到組id os.getuid() 得到用戶id os.geteuid() 得到有效用戶id os.setegid os.setegid() os.seteuid() os.setuid() os.getgruops() 得到用戶組名稱列表 os.getlogin() 得到用戶登錄名稱 os.getenv 得到環(huán)境變量 os.putenv 設置環(huán)境變量 os.umask 設置umask os.system(cmd) 利用系統(tǒng)調用,運行cmd命令
內置模塊(不用import就可以直接使用)常用內置函數(shù): help(obj) 在線幫助, obj可是任何類型 callable(obj) 查看一個obj是不是可以像函數(shù)一樣調用 repr(obj) 得到obj的表示字符串,可以利用這個字符串eval重建該對象的一個拷貝 eval_r(str) 表示合法的python表達式,返回這個表達式 dir(obj) 查看obj的name space中可見的name hasattr(obj,name) 查看一個obj的name space中是否有name getattr(obj,name) 得到一個obj的name space中的一個name setattr(obj,name,value) 為一個obj的name space中的一個name指向vale這個object delattr(obj,name) 從obj的name space中刪除一個name vars(obj) 返回一個object的name space。用dictionary表示 locals() 返回一個局部name space,用dictionary表示 globals() 返回一個全局name space,用dictionary表示 type(obj) 查看一個obj的類型 isinstance(obj,cls) 查看obj是不是cls的instance issubclass(subcls,supcls) 查看subcls是不是supcls的子類
類型轉換 chr(i) 把一個ASCII數(shù)值,變成字符 ord(i) 把一個字符或者unicode字符,變成ASCII數(shù)值 oct(x) 把整數(shù)x變成八進制表示的字符串 hex(x) 把整數(shù)x變成十六進制表示的字符串 str(obj) 得到obj的字符串描述 list(seq) 把一個sequence轉換成一個list tuple(seq) 把一個sequence轉換成一個tuple dict(),dict(list) 轉換成一個dictionary int(x) 轉換成一個integer long(x) 轉換成一個long interger float(x) 轉換成一個浮點數(shù) complex(x) 轉換成復數(shù) max(...) 求最大值 min(...) 求最小值 ------
There are three built-in data structures in python - list, tuple and dictionary.
list是處理一組有序項目的數(shù)據(jù)結構,即你可以在一個列表中存儲一個序列的項目。
列表是一種可變的數(shù)據(jù)類型。
python listname = [item1.item2,item3] listname.sort() listname.append(item4) del listname[0]
元組與列表極其類似,只不過元組和字符串一樣是不可變 即使你不能修改元組。元組通過圓括號中用逗號分割的項目定義。
元組最通常的用法是用在打印語句中,下面是一個例子:
print '%sis %d' % (name,age)
字典有鍵和值二元組,鍵是不可變的對象,字典的值可以任意。鍵值對在字典中以這樣的方式標記
d ={key1:value1,key2:value2}
序列是列表,元組,字符串的總稱,它的特點在于兩個操作--索引操作符 (indexing/subscription)、切片操作符(slicing)
list[-1],list[0],list[1],list[3] list[0;2] #0到1的 不包含2 list[2:] #2以后 list[:] #全部
當你創(chuàng)建一個對象并給它賦一個變量的時候,這個變量僅僅引用那個對象,而不是表示那個對象本身
!也就是說,變量名只是指向計算機中存儲那個對象的內存。這被稱作名稱到對象的綁定。
```python #!/usr/bin/python #-- coding=utf-8 -- print 'Simple Assignment' shoplist = ['apple','mango','carrot','banana'] mylist = shoplist #簡單的賦值 只是引用變量名 del shoplist[0] del mylist[0] print 'shoplist is',shoplist print 'mylist is',mylist print 'Coping by making full slice' mylist = shoplist[:] del mylist[0] print 'shoplist is',shoplist print 'mylist is',mylist ``` Simple Assignment shoplist is ['carrot', 'banana'] mylist is ['carrot', 'banana'] Coping by making full slice shoplist is ['carrot', 'banana'] mylist is ['banana']
很明顯,普通引用只是名稱的綁定,3而只有完整切片才是真正意義上的復制。所以我們在簡單引用后一定要考慮是否可以更改,因為操作可能影響到源對象。
注意在python中即使是整型也會被視為對象,這與C++和Java(1.5以前),在它們那兒整數(shù)是原始的內置類型。
在python中秉承一切皆對象的原則。
字段(Filed):屬于某個對象或類的變量
方法(Method):屬于類的函數(shù)
屬性(Attribute):上者綜合
-self
類方法與普通函數(shù)的區(qū)別所在,將類函數(shù)參數(shù)項前面用self修飾。與C++中this作用類似。
python class Person: def say_hi(self): print('Hello,how are you?')
Python中 特殊意義的類函數(shù)名稱
init 方法
該方法會在類的對象被實例化(Instantiated)時立即運行。這一方法可以用作初始化操作。
python class Person: def __init__(self,name) self.name = name def say_hi(self): print('Hello,my name is',self.name) p = Person('Swaroop') p.say_hi()
特殊變量命名方法
1、 _xx 以單下劃線開頭的表示的是protected類型的變量。即保護類型只能允許其本身與子類進行訪問。若內部變量標示,如: 當使用“from M import”時,不會將以一個下劃線開頭的對象引入 。
2、 __xx 雙下劃線的表示的是私有類型的變量。只能允許這個類本身進行訪問了,連子類也不可以用于命名一個類屬性(類變量),調用時名字被改變(在類FooBar內部,__boo變成_FooBar__boo,如self._FooBar__boo)
3、 __xx__定義的是特列方法。用戶控制的命名空間內的變量或是屬性,如init , __import__或是file 。只有當文檔有說明時使用,不要自己定義這類變量。 (就是說這些是python內部定義的變量名)
在這里強調說一下私有變量,python默認的成員函數(shù)和成員變量都是公開的,沒有像其他類似語言的public,private等關鍵字修飾.但是可以在變量前面加上兩個下劃線"_",這樣的話函數(shù)或變量就變成私有的.這是python的私有變量軋壓(這個翻譯好拗口),英文是(private name mangling.) **情況就是當變量被標記為私有后,在變量的前端插入類名,再類名前添加一個下劃線"_",即形成了_ClassName__變量名.**
The above is the detailed content of Python basic knowledge learning. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Integrating Postman applications on CentOS can be achieved through a variety of methods. The following are the detailed steps and suggestions: Install Postman by downloading the installation package to download Postman's Linux version installation package: Visit Postman's official website and select the version suitable for Linux to download. Unzip the installation package: Use the following command to unzip the installation package to the specified directory, for example /opt: sudotar-xzfpostman-linux-x64-xx.xx.xx.tar.gz-C/opt Please note that "postman-linux-x64-xx.xx.xx.tar.gz" is replaced by the file name you actually downloaded. Create symbols

The main difference between Java and other programming languages ??is its cross-platform feature of "writing at once, running everywhere". 1. The syntax of Java is close to C, but it removes pointer operations that are prone to errors, making it suitable for large enterprise applications. 2. Compared with Python, Java has more advantages in performance and large-scale data processing. The cross-platform advantage of Java stems from the Java virtual machine (JVM), which can run the same bytecode on different platforms, simplifying development and deployment, but be careful to avoid using platform-specific APIs to maintain cross-platformity.

Setting the location of the interpreter in PyCharm can be achieved through the following steps: 1. Open PyCharm, click the "File" menu, and select "Settings" or "Preferences". 2. Find and click "Project:[Your Project Name]" and select "PythonInterpreter". 3. Click "AddInterpreter", select "SystemInterpreter", browse to the Python installation directory, select the Python executable file, and click "OK". When setting up the interpreter, you need to pay attention to path correctness, version compatibility and the use of the virtual environment to ensure the smooth operation of the project.

The steps to manually install the plug-in package in VSCode are: 1. Download the .vsix file of the plug-in; 2. Open VSCode and press Ctrl Shift P (Windows/Linux) or Cmd Shift P (Mac) to call up the command panel; 3. Enter and select Extensions:InstallfromVSIX..., then select .vsix file and install. Manually installing plug-ins provides a flexible way to install, especially when the network is restricted or the plug-in market is unavailable, but attention needs to be paid to file security and possible dependencies.

[Common Directory Description] Directory/bin stores binary executable files (ls, cat, mkdir, etc.), and common commands are generally here. /etc stores system management and configuration files/home stores all user files. The root directory of the user's home directory is the basis of the user's home directory. For example, the home directory of the user user is /home/user. You can use ~user to represent /usr to store system applications. The more important directory /usr/local Local system administrator software installation directory (install system-level applications). This is the largest directory, and almost all the applications and files to be used are in this directory. /usr/x11r6?Directory for storing x?window/usr/bin?Many

Understanding Nginx's configuration file path and initial settings is very important because it is the first step in optimizing and managing a web server. 1) The configuration file path is usually /etc/nginx/nginx.conf. The syntax can be found and tested using the nginx-t command. 2) The initial settings include global settings (such as user, worker_processes) and HTTP settings (such as include, log_format). These settings allow customization and extension according to requirements. Incorrect configuration may lead to performance issues and security vulnerabilities.

The installation and configuration of MySQL can be completed through the following steps: 1. Download the installation package suitable for the operating system from the official website. 2. Run the installer, select the "Developer Default" option and set the root user password. 3. After installation, configure environment variables to ensure that the bin directory of MySQL is in PATH. 4. When creating a user, follow the principle of minimum permissions and set a strong password. 5. Adjust the innodb_buffer_pool_size and max_connections parameters when optimizing performance. 6. Back up the database regularly and optimize query statements to improve performance.

Informix and MySQL are both popular relational database management systems. They perform well in Linux environments and are widely used. The following is a comparison and analysis of the two on the Linux platform: Installing and configuring Informix: Deploying Informix on Linux requires downloading the corresponding installation files, and then completing the installation and configuration process according to the official documentation. MySQL: The installation process of MySQL is relatively simple, and can be easily installed through system package management tools (such as apt or yum), and there are a large number of tutorials and community support on the network for reference. Performance Informix: Informix has excellent performance and
