Home> System Tutorial> LINUX> body text

Python basic knowledge learning

PHPz
Release: 2024-08-17 07:42:32
Original
484 people have browsed it

Python basic knowledge learning

Python 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.

python function

Function is defined through the def keyword and looks like

python def function (arg1,arg2,...): ... fuction(1,2,...) #call function
Copy after login

DocStringsdocstrings

DocStrings Docstrings are an important tool for interpreting documentation programs.

``` python def function(): ''' say something here! ''' pass ... print function.__doc__ #调用doc ```
Copy after login

*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

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
Copy after login

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]]
Copy after login

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.

dir() function

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.

globals() and locals() functions

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.

Packages in Python

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

系统相关的信息模块: import sys sys.argv 是一个 list,包含所有的命令行参数. sys.stdout sys.stdin sys.stderr 分别表示标准输入输出,错误输出的文件对象. sys.stdin.readline() 从标准输入读一行 sys.stdout.write("a") 屏幕输出a sys.exit(exit_code) 退出程序 sys.modules 是一个dictionary,表示系统中所有可用的module sys.platform 得到运行的操作系统环境 sys.path 是一个list,指明所有查找module,package的路径.
Copy after login
操作系统相关的调用和操作: import os os.environ 一个dictionary 包含环境变量的映射关系 os.environ["HOME"] 可以得到环境变量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 得到环境变量 os.putenv 设置环境变量 os.umask 设置umask os.system(cmd) 利用系统调用,运行cmd命令
Copy after login
内置模块(不用import就可以直接使用)常用内置函数: help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像函数一样调用 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的子类
Copy after login
类型转换 chr(i) 把一个ASCII数值,变成字符 ord(i) 把一个字符或者unicode字符,变成ASCII数值 oct(x) 把整数x变成八进制表示的字符串 hex(x) 把整数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) 转换成一个浮点数 complex(x) 转换成复数 max(...) 求最大值 min(...) 求最小值 ------
Copy after login
Data structure

There are three built-in data structures in python - list, tuple and dictionary.

list

list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。

列表是一种可变的数据类型。

python listname = [item1.item2,item3] listname.sort() listname.append(item4) del listname[0]
Copy after login
元组(Tuples)

元组与列表极其类似,只不过元组和字符串一样是不可变 即使你不能修改元组。元组通过圆括号中用逗号分割的项目定义。

元组最通常的用法是用在打印语句中,下面是一个例子:

print '%sis %d' % (name,age)

字典(Dictionary)

字典有键和值二元组,键是不可变的对象,字典的值可以任意。键值对在字典中以这样的方式标记

d ={key1:value1,key2:value2}

序列(Sequence)

序列是列表,元组,字符串的总称,它的特点在于两个操作--索引操作符 (indexing/subscription)、切片操作符(slicing)

list[-1],list[0],list[1],list[3] list[0;2] #0到1的 不包含2 list[2:] #2以后 list[:] #全部
Copy after login
引用

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅引用那个对象,而不是表示那个对象本身
!也就是说,变量名只是指向计算机中存储那个对象的内存。这被称作名称到对象的绑定。

```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']
Copy after login

很明显,普通引用只是名称的绑定,3而只有完整切片才是真正意义上的复制。所以我们在简单引用后一定要考虑是否可以更改,因为操作可能影响到源对象。

面向对象编程

注意在python中即使是整型也会被视为对象,这与C++和Java(1.5以前),在它们那儿整数是原始的内置类型。
在python中秉承一切皆对象的原则。
字段(Filed):属于某个对象或类的变量
方法(Method):属于类的函数
属性(Attribute):上者综合
-self
类方法与普通函数的区别所在,将类函数参数项前面用self修饰。与C++中this作用类似。

python class Person: def say_hi(self): print('Hello,how are you?')
Copy after login

Python中 特殊意义的类函数名称
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()
Copy after login

特殊变量命名方法
1、 _xx 以单下划线开头的表示的是protected类型的变量。即保护类型只能允许其本身与子类进行访问。若内部变量标示,如: 当使用“from M import”时,不会将以一个下划线开头的对象引入 。
2、 __xx 双下划线的表示的是私有类型的变量。只能允许这个类本身进行访问了,连子类也不可以用于命名一个类属性(类变量),调用时名字被改变(在类FooBar内部,__boo变成_FooBar__boo,如self._FooBar__boo)

3、 __xx__定义的是特列方法。用户控制的命名空间内的变量或是属性,如init , __import__或是file 。只有当文档有说明时使用,不要自己定义这类变量。 (就是说这些是python内部定义的变量名)

在这里强调说一下私有变量,python默认的成员函数和成员变量都是公开的,没有像其他类似语言的public,private等关键字修饰.但是可以在变量前面加上两个下划线"_",这样的话函数或变量就变成私有的.这是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!

source:linuxprobe.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!