Python a review

Python melted 1 review

variable

Similar Python variables and variable C language notation;

Writing requirements

python programming structure use indention, abandoned braces;

structure

Branch:

if(条件语句1):
    执行语句块
else if(条件语句2):
    执行语句块
else:
    执行语句块

cycle:

while loop

while 循环条件:
    循环语句体

for loop

for 目标 in 表达式:
    循环语句体

Expression of results and objectives linked to SADC

  • range () function:

Step function;

range (x, y, z)

x: start

y: End (y-1)

z: step

  • break statement:

Out of the current structure

  • continue statement:

End run this loop body

List

Create a list

>>> num = [1,2,3,4,5] // 列表创建
>>> num               // 列表输出
[1, 2, 3, 4, 5]
>>> num = ['Hello','你好',666]
>>> num // 列表支持各种类型,除数字以外的其他字符都需要用单引号
['Hello', '你好', 666]

append (): Adding elements

>>> num.append(6)
>>> num
[1, 2, 3, 4, 5, 6]

extend (): adding a plurality of elements

>>> num.extend([7,8,9])
>>> num
[1, 2, 3, 4, 5, 6, 7, 8, 9]

append () to add a single element, it is easy to expand;

And the original list extend () sucked and own list to be added together into a new list

insert (): insert elements in the list

>>> num.insert(0,0) // 在0索引位置添加元素0
>>> num
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

pop (): Delete list element

  • php (): Delete the last element of the list
  • php (X): Delete list index element X
  • pop () returns the element content to be deleted
>>> num.pop()
9
>>> num.pop(0)
0
>>> num
[1, 2, 3, 4, 5, 6, 7, 8]

del statement: delete the list

  • del [ListName]: delete the entire list (you can also delete multiple simultaneous)
  • To delete an element index of X: del [ListName [X]]
>>> num = [1,2,3,4,5,6,7,8]
>>> num
[1, 2, 3, 4, 5, 6, 7, 8]
>>> del num[7]
>>> num
[1, 2, 3, 4, 5, 6, 7]
>>> del num
>>> num
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    num
NameError: name 'num' is not defined

Such as error prompt: num does not exist

remove (): Delete the known elements X

  • Search for and delete the content of the element X

Our previous statements and del pop () functions are relying index list to delete elements in the index, remove () is not on the index, but to delete according to the specific content elements.

>>> num = ['Hello','你好',666]
>>> num
['Hello', '你好', 666]
>>> num.remove(666)
>>> num
['Hello', '你好']
>>> num.remove('你好')
>>> num
['Hello']

List slicing

The output or display a list of only a portion or copy data elements, the so-called list slicing

>>> num = ['HUAWEI',"CHINA",'Mirror','XIAOMI']
>>> num
['HUAWEI', 'CHINA', 'Mirror', 'XIAOMI']
>>> num[0:1]
['HUAWEI']
>>> num[0:2]
['HUAWEI', 'CHINA']
>>> num[0:4]
['HUAWEI', 'CHINA', 'Mirror', 'XIAOMI']

>>> num[:2]
['HUAWEI', 'CHINA']
>>> num[:]
['HUAWEI', 'CHINA', 'Mirror', 'XIAOMI']
>>> num[2:]
['Mirror', 'XIAOMI']

Careful observation, found fragments of [x: y] left and right to open and close range (in principle) [python in a lot of time and extent of closure issues are left open closed principle of the right]

Meanwhile, the fragmentation mechanism also supports a range of values ​​is omitted; i.e. from zero left blank, the blank to the right of the end of the last element, all elements of the left and right outputs are all null;

Advanced Gameplay sliced

Everyone thinks fragment only two parameters?

There are three parameters fragment ==> [x: y: z]

x: start

y: end

z: the step size (i.e., each time incrementing the number of z can be understood as the concept of arithmetic Mathematics)

>>> num = [] // 创建一个空数组
>>> for i in range(1,10):
    num.append(i)
>>> num
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> num[0:10:2]
[1, 3, 5, 7, 9]

Copy the early depth discussion

>>> list = [1,2,3,4]
>>> copy = list
>>> copy1 = list
>>> copy2 = list[:]
>>> copy1
[1, 2, 3, 4]
>>> copy2
[1, 2, 3, 4]

As can be seen from the top, list directly copy and list [:] Like result of the segment to copy, but in fact hidden impatient Oh!

>>> list.append(5)
>>> copy1
[1, 2, 3, 4, 5]
>>> copy2
[1, 2, 3, 4]

Adding an element to the original source list append (), the source list and a list of contents found together copy1 not change (the append () operation)

  • Explanation:

copy1 = list: the list of memory addresses belonging to the copy1,

copy2 = list [:]: a list of values ​​belonging to the copy2

Compare List

List of supported comparison operators comparison operators:

>>> list1 = [123]
>>> list2 = [234]
>>> list3 = [123]
>>> list1 < list2
True
>>> list1 <= list3
True
>>> list1 == list3
True
>>> list1 != list2
True
>>> list1.append(234)
>>> list2.append(123)

>>> list1
[123, 234]
>>> list2
[234, 123]
>>> list1 > list2
False

Comparison of two according to the size of the list is the ASCII value of the comparison, if they are two elements, the first comparison, if the first element of the same in the second comparison.

List of strings

Stitching and repeat

>>> str1
['HUAWEI']
>>> str2
['CHINA']
>>> str1 + str2
['HUAWEI', 'CHINA']
>>> str1 * 3
['HUAWEI', 'HUAWEI', 'HUAWEI']
>>> str1 = str1 +str2
>>> str1
['HUAWEI', 'CHINA']
>>> str1[1] * 3
'CHINACHINACHINA'

Elements of judgment: in / not in

  • Determine whether there are elements of the list: 'str' in List / 'str' not in List
>>> str1
['HUAWEI', 'CHINA']
>>> "CHINA" in str1
True
>>> "CHINA" not in str1
False

Query element

index (): Query element index

>>> str = ["H","U","A","W","E","I"]
>>> str
['H', 'U', 'A', 'W', 'E', 'I']
>>> str.index("I")
5
>>> str.index("K")  // 元素不存在保存
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    str.index("K")
ValueError: 'K' is not in list
>>> 

count (): Query element repetitions

>>> list
[3, 4, 5, 2, 5, 66, 7, 2, 5, 7]
>>> list.count(5)
3

Sort: reverse (), sort ()

  • reverse (): oppositely oriented
  • sort (): ascending
>>> list
[3, 4, 5, 2, 5, 66, 7, 2, 5, 7]
>>> list.reverse() // 反向排列
>>> list
[7, 5, 2, 7, 66, 5, 2, 5, 4, 3]
>>> list.sort()   // 升序
>>> list
[2, 2, 3, 4, 5, 5, 5, 7, 7, 66]
>>> list.reverse()  // 反向排列 (srot+reverse ==> 降序)
>>> list
[66, 7, 7, 5, 5, 5, 4, 3, 2, 2]

Tuple

Tuples can be understood as: Once defined list can not be changed.

Create a tuple

>>> tuple = (1,2,3,4,5)
>>> number = [1,2,3,4,5]
>>> tuple
(1, 2, 3, 4, 5)
>>> number
[1, 2, 3, 4, 5]

tuple is a tuple, number is a list;

It can be found; both as defined differently

Tuple is a list composed of data of parentheses, the list is a set of data composed by square brackets

Tuple access

Tuples and lists access method is the same, the main access through the index of the tuple of the tuple element, and a list can be accessed by way of the same slice (slices).

>>> tuple
(1, 2, 3, 4, 5)
>>> tuple[2]
3
>>> tuple[3]
4
>>> tuple[:]
(1, 2, 3, 4, 5)

type () method

  • The return type of the parameter
>>> tup = ()
>>> num = []
>>> type(tup)
<class 'tuple'>
>>> type(num)
<class 'list'>

In many cases, we will consider a list of data is defined in parentheses tuples, but not!

>>> del tup
>>> tup
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    tup
NameError: name 'tup' is not defined
>>> tup = 1,2,3,4
>>> type(tup)
<class 'tuple'>

Yes, no parentheses is a list of data tuple tuple.

Tuple is defined characteristics: comma

>>> (6)*6
36
>>> (6,)*6
(6, 6, 6, 6, 6, 6)

Therefore, when the definition of a tuple, you need a comma tells the program, which is a tuple

>>> tup = (1,2,3,)
>>> type(tup)
<class 'tuple'>

This is the most standard definition method, and why?

Tuple update and delete

  • Update:

Tuples and lists functions almost the same except for changing the data, data of one tuple is not changed, but between tuples and tuples can be spliced

>>> tup
(1, 2, 3)
>>> tup = tup[:3] + 4, + 5,
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    tup = tup[:3] + 4, + 5,
TypeError: can only concatenate tuple (not "int") to tuple
>>> tup = tup[:3] + (4,) + (5,6,)
>>> tup
(1, 2, 3, 4, 5, 6)

The use of stitching tup tup tuple data is updated;

note:

Here, when the stitching, the stitching content are in parentheses and commas and other signs indicate that this is a tuple of data, otherwise it will be considered a procedural character or numeric data.

Comma is a sign of the definition of tuples

  • delete:
>>> tup = tup[:2] + tup[4:]
>>> tup
(1, 2, 5, 6)

Overwrite the element to be deleted by splicing method, in order to achieve the purpose of deleting elements.

  • to sum up:

Data tuple is unchanged, but tuples and lists can be as free of stitching:

Use sliced ​​stitching at the end of a way to make elements adding elements (note tuple element identifies the comma)

Using the mosaic tile embodiment of the cutting element to delete content before and after splicing into a new tuple

String

  • Python3 all strings are Unicode (encoded) string

create

>>> char = "HUAWEI"
>>> str = 'XIAOMI'
>>> char
'HUAWEI'
>>> str
'XIAOMI'

It can be used to create a string of single and double quotes

Modify the string

>>> str = str[:3] + "-" + str[3:]
>>> str
'XIA-OMI'

Tuple string modifications and similar, use slice splicing manner change the string content.

ps: re-form a new string to a new string variable so be assigned

String formatting

format()

  • According to index coordinate
>>> '{0}-{1}={2}'.format('XIAOMI','HUAWEI','CHINA')
'XIAOMI-HUAWEI=CHINA'

As can be seen from the code, the contents of the braces is a string of parameter values ​​corresponding to index the contents of this format method, popular saying: parameter values ​​corresponding curly braces format of the index will be composed of a string of calls. {Format parameters referred to: position parameter}

  • According to (keyword) key-value pairs
>>> '{x}-{h}={c}'.format(x='XIAOMI',h='HUAWEI',c='CHINA')
'XIAOMI-HUAWEI=CHINA'
  • Note: The location parameter index to be placed in front of a keyword index

The format operation

Formatting operator

Format Symbol description
%c ASCII characters and formatting
%s Format string
%d Integer format (decimal)
%O Formatting unsigned octal
%x 、%X Format Unsigned hexadecimal (lowercase, uppercase)
%f Floating-point format
%and is Floating-point format in scientific notation

Common format for the above symbolic representations of operations; and similar to the C language.

Write format operation

'[格式化操作符]' % [需要格式化操作的内容]
>>> '%c' % 99
'c'

Formatting operation expressions are: Percent ==> %

Auxiliary parameter

Parameters command description
m.n m is from a minimum width, n is the number of digits after the decimal point
- Left
+ Before the certificate plus a good show
# It is shown in decimal and octal result: 0o and the 0x / 0X
0 Number preceded by "0" padded with spaces
Escape character description
 ' apostrophe
 " Double quotes
 a Sound systems Ming
 b Backspace
 n Newline
 t ,  v Tabs (eight spaces)
 f Page breaks
 r Carriage return
 \ Backslash
 0 It represents a null character

sequence

  • Lists, tuples, strings (*) can be regarded as iterables

list (): iterable into a list

>>> list = list((1,2,3,4))
>>> list
[1, 2, 3, 4]
>>> list = list("HUAWEI")
>>> list
['H', 'U', 'A', 'W', 'E', 'I']

tuple (): iterables into tuples

>>> tuple = tuple("HUAWEI")
>>> tuple
('H', 'U', 'A', 'W', 'E', 'I')
>>> type(tuple)
<class 'tuple'>

str (): obj the object into a string

>>> s = str(1)
>>> s
'1'
>>> type(s)
<class 'str'>
>>> tuple(s)
('1',)

len (sub): Returns the parameter length

>>> num = [1,2,3,5,6,7]
>>> len(num)
6

max () / min (): Sequence Max / Min

>>> num = [1,2,3,5,6,7]
>>> len(num)
6
>>> max(num)
7
>>> min(num)
1

sum (): returns the sum

>>> num = [1,2,3,5,6,7]
>>> sum(num)
24

sorted (): Sort

>>> num
[12, 24, 33, 32, 243, 3, 6, 23, 15, 7, 6, 5, 3, 2, 1]
>>> sorted(num)
[1, 2, 3, 3, 5, 6, 6, 7, 12, 15, 23, 24, 32, 33, 243]
>>> num
[12, 24, 33, 32, 243, 3, 6, 23, 15, 7, 6, 5, 3, 2, 1]
>>> num.sort()
>>> num
[1, 2, 3, 3, 5, 6, 6, 7, 12, 15, 23, 24, 32, 33, 243]

Code in front of us and sort () compared found

sorted (): returns the result without changing the original data in ascending

sort (): the source list in ascending

reversed (): Reverse Iteration

>>> list = list((2,4,67,3,7,3,8))
>>> for i in reversed(list):
    print(i,end='-')

8-3-7-3-67-4-2-

As can be seen, reverse the reversed sequence () method converts an output iterator

enumerate (): generating a tuple

Tuple: 2 tuples of elements constituting an iterator objects, each tuple has an index parameter and a corresponding element in the iteration composition.

>>> for i in enumerate(list):
    print(i)

    
(0, 'H')
(1, 'U')
(2, 'A')
(3, 'W')
(4, 'E')
(5, 'I')

zip (): Iterative combined parameter tuple

Returns iteration parameter tuple composed of

>>> list
[2, 4, 67, 3, 7, 3, 8]
>>> str
['H', 'U', 'A', 'W', 'E', 'I']
>>> for i in zip(list,str):
    print(i)

    
(2, 'H')
(4, 'U')
(67, 'A')
(3, 'W')
(7, 'E')
(3, 'I')

function

Function to create, call

Function meaning that would be required and repeat function code is encapsulated in an object function, the need to use a direct call to.

def out():
    print("Hello,World!")
    print("I am Mirror")
    
out() // 调用out函数
Hello,World!
I am Mirror

Function Arguments

When the function is defined, you can add in parentheses parameter settings, set the parameters for the function, the function call will be asked to pass parameters, the function body can also refer to this parameter to work.

def name(s):
    print(s)

def sum(x,y):
    print(x+y)

name("Mirror")
sum(1,2)
================ RESTART ================
Mirror
3

Function may receive zero or more parameter values, when the function definition, the data type of the parameter may not be defined

Function return value

def name(s):
    return "I am {0}".format(s)

def sum(x,y):
    return "SUM = {0}".format(x+y)

print (name("Mirror"))
print (sum(1,2))
================ RESTART================
I am Mirror
SUM = 3

Flexible function

And parameter arguments

We learned from the example of function parameters to set and pass parameters, but if we do not know how many data parameters we pass the time how to do?

  • Parameter: the parameter defines the function when creating
  • Argument: the calling procedure calls a function with a parameter passed

Function Documentation

  • Refers to a specific role in the function definition below the specified function, increase readability

In general, three quotation marks at the beginning whine it's not printed out, but still will be very similar to the store, and annotation features, we can get the three lead content in the time of the call, understand the role of the function

_ _ Doc _ _: get function
def sum(x,y):
    """ 返回 x,y 的求和"""
    return "SUM = {0}".format(x+y)

print (sum.__doc__)
================ RESTART ================
 返回 x,y 的求和

Keywords function

def sum(x,y):
    """ 返回 x,y 的求和"""
    return "SUM = {0}".format(x+y)

print (sum(x=1,y=2))

The parameter name as a key, the "assignment" mode parameter passing arguments to the specified shape

The default parameters

def sum(x=1,y=2):
    """ 返回 x,y 的求和"""
    return "SUM = {0}".format(x+y)

print (sum())

Default parameters: parameter function definition simultaneously to a default parameter setting parameters, if the received function call arguments passed parameter is used to run the default parameters

variable parameter

Back parameter proposed do not know about the arguments:

We learned from the example of function parameters to set and pass parameters, but if we do not know how many data parameters we pass the time how to do?

This time we need to set a variable parameter (parameters):

* Katachisan name

def sum(* s):

    print(len(s))
    print(type(s))

sum(1,2,3,4,5,6,7)

================ RESTART ================
7
<class 'tuple'>

Analysis results were observed: the use of an asterisk-shaped participants received sequence argument automatically compressed into a "tuple", we can only pass a single (numeric, character, string) is not used when the parameter variable parameter

  • The variable parameter may be received are: iterative sequence can be (a list of tuples, characters, strings, ......)

Dictionary collection

  • python set of dictionaries employed: (Key: Value) stored key-value pairs, reading and other operations

Create dictionary (dict)

>>> dict = {1:10086,"a":"CHINA"}
>>> dict
{1: 10086, 'a': 'CHINA'}
>>> dict[1]  // 根据Key索引并返回Value
10086
>>> dict["a"]
'CHINA'

Dictionary logo feature: flowers surrounded by parentheses key sequence

  • Key: it is unique and will not be repeated in the same dictionary collection
  • Value: Value corresponding to each of a Key, Value may be repeated but must be immutable

Dictionary built-in actions

formkeys (): Returns a new dictionary is created

  • parameter:
    • key: must
    • Value: Default None
>>> del dict
>>> dict.fromkeys((1,2,3))
{1: None, 2: None, 3: None}

Returns the contents of the dictionary

keys (): Returns the value of the dictionary All Key
>>> dict
{1: None, 2: None, 3: None}
>>> dict.keys()
dict_keys([1, 2, 3])
values ​​(): Returns the value of the dictionary all Value
>>> dict.values()
dict_values([None, None, None])
items (): Returns the dictionary all
>>> dict.items()
dict_items([(1, None), (2, None), (3, None)])

get (): Query of a key value

>>> dict
{1: 10086, 'a': 'CHINA'}
>>> dict.get("a")
'CHINA'
>>> dict.get(1)
10086
>>> dict.get("CHINA")
>>> dict.get(112)

get () query a key, if there is no error will not return! It can be used in / not in determining whether there is achieved

claer (): Empty dictionary

>>> dict.clear()
>>> dict
{}

ps: Empty contents are not deleted

copy (): Copy the dictionary

>>> dict
{1: 10086, 'a': 'CHINA'}
>>> c = {} // 定义一个空字典
>>> c
{}
>>> type(c)
<class 'dict'>
>>> c = dict.copy()
>>> c
{1: 10086, 'a': 'CHINA'}

pop (): pop-up (delete) value

  • pop (key): Delete key and the corresponding value
  • popitem (): delete the last key and value
>>> dict = {1:10086,"a":"CHINA"}
>>> dict.pop(1)
10086
>>> dict
{'a': 'CHINA'}
>>> dict = {1:10086,"a":"CHINA"}
>>> dict.popitem()
('a', 'CHINA')
>>> dict
{1: 10086}

update (): update the dictionary

  • dict.update(dict)
>>> dict.update({2:2019})
>>> dict
{1: 10086, 'a': 'CHINA', 2: 2019}

Create a collection (set)

  • Look at the difference and set the dict
>>> dict1 = {}
>>> dict2 = {1,2,3,4,5} // 集合创建
>>> type(dict1)
<class 'dict'>
>>> type(dict2)
<class 'set'>

Feature set can be found by comparing the set of dictionary:

Collection is the use of braces but not to key-value pairs, separated by commas sequence

  • Start a collection
>>> set = {1,2,3,4,5,6}

Access to the collection

>>> set1
{1, 2, 3, 4, 5, 6}
>>> for i in set1:
    print(i,end=" ")

1 2 3 4 5 6

Python file

Open the file open ()

Operators

Mark description
r Open the file in read-only mode
w Open a file for writing
x File exists will throw an exception
a Open for writing, can be added to an existing file
b Open the file in binary
t Textually open
+ Read-write mode
The Universal newline support

open () function

open (): for creating a file object to other operations using the file object

  • Single parameter: Can be specific path and file name of the file (if only the file name will index the current directory)
  • Operator: decision file open mode (read-only default "r")

Manipulation Functions

close (): Close the file

read (): reads characters

  • read (size = -1): read the contents of the specified character size from the size of the file; unassigned means to read the entire contents and returns a String

readline (): read a line of string

write (): output content to a file

writelines (): output sequence to a file

seek (): move the file pointer

  • seek (offset, form): offset bytes from form
    • offset:0 = 起始;1 = 当前位置;2 = 末尾

tell():返回当前文件的位置

OS 文件模块

os模块;import os 导入os模块

目录操作

getcwd():获取当前目录
chdir():切换目录
listdir():查看任意目录内容
mkdir():创建文件夹(目录)
makedirs():创建多级文件夹(目录)

删除操作

remove():删除指定文件
radir():删除指定文件夹(目录)
removedirs():删除多级文件夹(目录)
rename():文件/文件夹 重命名

系统操作

system():调用工具
walk():遍历子目录返回三元组

path 路径操作

path.basename():获取文件名
path.dirname():获取路径名
path.join():完整路径join
path.split():分隔路径和文件名
path.splitext():分隔文件名和扩展名
path.getsize():获取文件大小(字节)

path 时间函数

path.getatime():最近访问时间
path.getctime():创建时间
path.getmtime():修改时间

prckle()模块

可以将对象以文件的形式存放在磁盘中;是一种简单的持久化功能

python的所有数据类型都可以使用 prckle()来序列化存放磁盘

异常处理

AssertionError:断言

assert在测试程序的时候,在代码植入检查点

>>> list = ['Mirror']
>>> assert len(list)>0
>>> list.pop()
'Mirror'
>>> assert len(list)>0
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(list)>0
AssertionError

assert断言:在其语句后面的条件成立的时候则不会编译assert,若断言条件满足后则会在程序中报错。

如上例代码程序:原先list列表内有一个元素,assert没有报错,但是pop方法弹出(删除)元素后,assert的条件得不到满足就会报错

try - except语句

try:
    检测范围
except exception[as e]:
    检测发现exception异常后的处理方法
finally:// 可选
    必须执行的代码块
  • 范例:
>>> try:
        file = open("a.txt")
        file.close()
    except OSError:
        print("Error")

    
Error

如范例中的程序,检测到在调用file文件对象的时候发生了OSError错误,由此执行报错(异常)代码执行块

>>> try:
        file = open("a.txt")
        file.close
    except OSError as e:
        print(str(e) + "Error")
    except TypeError as e:
        print(str(e) + "Error")

    
[Errno 2] No such file or directory: 'a.txt'Error

如上;利用as error方法,将错误信息写入e变量中,在以str的类型输出错误信息;同时发现,可以定义多种不同的错误类型和报错输出。

异常

Exception: 所有异常的基类(可以接收任何类的异常)

AssertionError:assert语句失败(assert条件不成立)

AttributeError:访问一个对象没有的属性(对象属性不存在)

IOError:输入输出操作异常

ImportError:无法引入模块或包(路径错误等)

IndexError:索引超出序列边界

KeyError:访问字典中不存在的key

KeyboardInterrupt:Ctrl+C被触发

NamError:使用的对象无变量

SyntaxError:代码逻辑语法错误

TypeError:对象类型和语句要求不符

UnboundLocalError:全局变量的异常

ValueError:传入的value值异常出错

ZeroDivisonError:触发除零的异常

第三方GUI模块:EasyGUI

类和对象

认识类和对象

类:class 类名称:

对象:def 方法名():

一个程序可以由多个类组成,一个类由多个对象方法组成;

self关键字:代表自己的对象参数

类的方法与普通的函数只有一个区别:它们必须有一个额外的参数名称,但在调用这个方法的时候不可以为这个参数赋值,python会提供这个值。这个特别的变量指的是对象的本身,名为:self;

初探Python魔法方法

__ init__()构造方法

只要实例化一个对象前,这个方法就会在对象被创建前自动调用;参数形参也会自动传入该方法中;可以利用重写该方法实现初始化的操作

class Potate:
    def __init__(self.name):
        self.name = name
    def kick(self):
        pirnt(self.name)

公有和私有

public :公有、公共

private:私有

以上是C++和Java方法;

在Python中表示私有的属性:变量名前两个下划线“__”

继承

class 类名(被继承的类):
  • self:只可以使用自己的类中的对象
  • super:可以从子类中调用父类中的属性对象

Python支持多重继承,即一个类继承多个父类;【不建议使用】

Guess you like

Origin www.cnblogs.com/wangyuyang1016/p/11260913.html