一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - python基礎之入門必看操作

python基礎之入門必看操作

2020-11-28 11:01Python教程網 Python

下面小編就為大家帶來一篇python基礎之入門必看操作。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

這里提供在使用python進行開發中常使用到的方法技巧,如有不對歡迎批評指正。

要點:開發中類、變量特性查詢,類型就是類,斷言的使用,深淺復制判斷等

python腳本文件是使用UTF-8編碼的,所以在發現中文字符出現亂碼時應當考慮是否文本文件采用UTF-8編碼。

如果想指定不同的編碼需要在源碼文件中開頭處添加這樣的注釋:

?
1
# -*- coding: utf-8 -*-

如果python在linux和unix系統中運行,需要在源碼的第一行添加:

?
1
#!/usr/bin/python3

如何獲取python中各個模塊,變量,類等的內容呢?

python中關于幫組的查詢可以通過變量__all__,__dict__,函數help(),dir()來獲取。

如果__all__在類,模塊中定義,一般包含著外部可以調用的特性,如果定義了沒有賦值,會自動使用非下劃線開頭的特性填充。如果沒有參數__all__python會提示AttributeError屬性錯誤。

__dict__一般會給出類或者模塊中定義的特性(包括屬性和方法),是以字典的形式輸出的使用元組來表示參數和參數值(參數,參數值或者描述)

list的__dict__查看

?
1
2
>>> list.__dict__
2 mappingproxy({'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, '__lt__': <slot wrapper '__lt__' of 'list' objects>, '__le__': <slot wrapper '__le__' of 'list' objects>, '__eq__': <slot wrapper '__eq__' of 'list' objects>, '__ne__': <slot wrapper '__ne__' of 'list' objects>, '__gt__': <slot wrapper '__gt__' of 'list' objects>, '__ge__': <slot wrapper '__ge__' of 'list' objects>, '__iter__': <slot wrapper '__iter__' of 'list' objects>, '__init__': <slot wrapper '__init__' of 'list' objects>, '__len__': <slot wrapper '__len__' of 'list' objects>, '__getitem__': <method '__getitem__' of 'list' objects>, '__setitem__': <slot wrapper '__setitem__' of 'list' objects>, '__delitem__': <slot wrapper '__delitem__' of 'list' objects>, '__add__': <slot wrapper '__add__' of 'list' objects>, '__mul__': <slot wrapper '__mul__' of 'list' objects>, '__rmul__': <slot wrapper '__rmul__' of 'list' objects>, '__contains__': <slot wrapper '__contains__' of 'list' objects>, '__iadd__': <slot wrapper '__iadd__' of 'list' objects>, '__imul__': <slot wrapper '__imul__' of 'list' objects>, '__new__': <built-in method __new__ of type object at 0x000000005BBAF530>, '__reversed__': <method '__reversed__' of 'list' objects>, '__sizeof__': <method '__sizeof__' of 'list' objects>, 'clear': <method 'clear' of 'list' objects>, 'copy': <method 'copy' of 'list' objects>, 'append': <method 'append' of 'list' objects>, 'insert': <method 'insert' of 'list' objects>, 'extend': <method 'extend' of 'list' objects>, 'pop': <method 'pop' of 'list' objects>, 'remove': <method 'remove' of 'list' objects>, 'index': <method 'index' of 'list' objects>, 'count': <method 'count' of 'list' objects>, 'reverse': <method 'reverse' of 'list' objects>, 'sort': <method 'sort' of 'list' objects>, '__doc__': "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"})

dir()會以列表的形式給出所有可以獲得的特性屬性,而不含有值和屬性描述:

list使用dir()查看

?
1
2
1 >>> dir(list)
2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

一般而言使用__dict__和dir()就可以了,當然很多時候也需要help()查看詳細的文檔(其實就是__doc__中的內容):

list使用help()查看

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
help(list)
Help on class list in module builtins:
 
class list(object)
 | list() -> new empty list
 | list(iterable) -> new list initialized from iterable's items
 |
 | Methods defined here:
 |
 | __add__(self, value, /)
 |  Return self+value.
 |
 | __contains__(self, key, /)
 |  Return key in self.
 |
 | __delitem__(self, key, /)
 |  Delete self[key].
 |
 | __eq__(self, value, /)
 |  Return self==value.
 |
 | __ge__(self, value, /)
 |  Return self>=value.
 |
 | __getattribute__(self, name, /)
 |  Return getattr(self, name).
 |
 | __getitem__(...)
 |  x.__getitem__(y) <==> x[y]
 |
-- More --

如果我們現在創建了一個對象 a = list(),現在想要獲取對象a有什么特性方法,也是使用dir()和help()。

在這里需要強調的是,dir()和help()的強大之處不僅僅可以查閱類,還可以我們定義的變量。這樣我們在編碼過程中能夠獲得更多的內容。

a=1中變量a含有方法的查找

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
>>> a=1
>>> dir(a)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> help(a)
Help on int object:
 
class int(object)
 | int(x=0) -> integer
 | int(x, base=10) -> integer
 |
 | Convert a number or string to an integer, or return 0 if no arguments
 | are given. If x is a number, return x.__int__(). For floating point
 | numbers, this truncates towards zero.
 |
 | If x is not a number or if base is given, then x must be a string,
 | bytes, or bytearray instance representing an integer literal in the
 | given base. The literal can be preceded by '+' or '-' and be surrounded
 | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
 | Base 0 means to interpret the base from the string as an integer literal.
 | >>> int('0b100', base=0)
 | 4
 |
 | Methods defined here:
 |
 | __abs__(self, /)
 abs(self)
 |
 | __add__(self, value, /)
 |  Return self+value.
 |
 | __and__(self, value, /)
 |  Return self&value.
 |
-- More --

變量和對象類型的查找等操作

python中除了使用dir(),help(),__all__,__dict__查看原來定義設計的內容外,可以使用很多已經定義的特性來獲取更多信息:

獲取變量類型和對象類型的方法:

通過__class__查詢變量和類類型

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>> a =1
>>> a.__class__
<class 'int'>
>>> b = 1.0
>>> b.__class__
<class 'float'>
>>> c = ''
>>> c.__class__
<class 'str'>
>>> d = list()
>>> d.__class__
<class 'list'>
>>> e = tuple()
>>> e.__class__
<class 'tuple'>
>>> f = dict()
>>> f.__class__
<class 'dict'>
>>> list.__class__
<class 'type'>
>>> dict.__class__
<class 'type'>
>>> tuple.__class__
<class 'type'>
>>> object.__class__
<class 'type'>
>>> None.__class__
<class 'NoneType'>

通過上面的代碼我們發現,如果class為type其實這個本身就是一個類的定義,如果是其他的則是對象。

你想過沒有,在python中基本的變量也是對象?

在一般語言中,我們的類型都分為整型,浮點型,字符串等等。但是在python這些類型其實都是類的形式定義的,而類也是繼承了頂級超類的。

使用__class__查看類型,__bases__查看超類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
>>> a = 1
>>> a.__class__
<class 'int'>
>>> int.__class__
<class 'type'>
>>> str.__class__
<class 'type'>
>>> bool.__class__
<class 'type'>
>>> list.__class__
<class 'type'>
>>> dict.__class__
<class 'type'>
>>> tuple.__class__
<class 'type'>
>>> type.__class__
<class 'type'>
>>> object.__class__
<class 'type'>
>>> type.__bases__
(<class 'object'>,)
>>> int.__bases__
(<class 'object'>,)
>>> str.__bases__
(<class 'object'>,)
>>> bool.__bases__
(<class 'int'>,)
>>> float.__bases__
(<class 'object'>,)
>>> object.__bases__
()
>>>

發現沒有,我們使用的類型其實都是類,除了bool繼承了類int,其他的都是繼承超類object。而object類沒有超類。應該說,type是一個類型類!當然None類型是NoneType,而NoneType卻不是類,這是說None是個空值。

type類中含有的內容和object類中含有的內容

?
1
2
3
4
>>> dir(type)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro']
>>> dir(object)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

is 和id()可以讓我們看清變量之間的隱藏關系!

我們都知道,python從在使用上有著弱類型的便捷性。當然在python中,相同數值的變量只有一個!這是為什么呢?這是因為他們都是指向同一個內存地址,可以將這些變量想象成他們存放的是一個個內存地址,我們對他們的賦值不過是將他們指向的內存地址做了改變!!

從指針的角度理解python是很有幫助的。變量本身存放的是指針,如果你這個能夠理解了,那么關于python的變量和內存回收機制就能夠很好理解并運用了。

A is B 操作的作用是判斷A是否是B,如果為真,則說明A與B是同一個對象,如果為假,則說明A與B不是同一個對象。

id(A) 操作的作用是判斷A在內存中的id序列號。

下面我們來詳細說明下python中的相關現象:

1.python中A和B雖然是同一個對象,但是當對A賦值之后,A與B再是同一個對象,因為python中的賦值是將A所所指向的地址改成了另一個對象的地址,這時候與B中的地址不一樣,B地址所致的對象的值不會收到A賦值影響。

2.python中同一個對象所具有的id可能是不同的,因為在沒有指向該地址的變量時,python內存自動清理會清理掉這個對象。再次使用到具有相同數值的對象可能是在前一個對象自動清理之后創建的新對象。

針對第一個情況我們首先通過對True和False和數字來確定哪些值對象的id是系統自帶的,即便這些值對象不被變量使用python內存清理也不會清理這些對象!

通過id來判斷數值和布爾值中的值對象是否是系統自帶的對象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
>>> id(True)
1538937056
>>> id(False)
1538937088
>>> id(False) - id(True)
32
>>> id(-5)
1539416992
>>> id(-6)
1667933956912
>>> id(-4)
1539417024
>>> id(-4)-id(-5)
32
>>> id(-3)-id(-4)
32
>>> id(-3)
1539417056
>>> id(-2)
1539417088
>>> id(-2) - id(-3)
32
>>> id(255)
1539425312
>>> id(256)
1539425344
>>> id(256) - id(255)
32
>>> id(257)
1667904611440
>>> id(1.0)
1667904643192

你會發現數字-5到256是連續的,他們相鄰的id值相差是32,意思是他們是32表示的數值。id返回的值就是他們在python中邏輯內存地址的值,在不同python進程中這些相同值對象返回的id值是一致的。而小于-5或者大于256的數值,小數,超過單個字符的字符串都是python在用戶使用時創建的值對象,在不同的python進程中相同的值的id是不同的!其他值在不使用時有的就會被python內存清理程序清理掉釋放內存!

python基礎之入門必看操作

當然,python中還有很多對象、類、函數等是python自創建的不會因為不使用而被內存清理程序清理掉。比如 int,None,dict,list。

不夠值得一提的是 None is None是返回True 。并且id(None)的返回值是1538983120。這說明與其他腳本(比如javascript)不一樣,None是空值,是一個唯一的空值對象,程序中所有的None都是相等的。都是同一個內存地址中存放的值。

很多情況下,我們想判斷兩個變量是否指向同一個內存地址塊存放的值,可以使用is來判斷。

python中對于全局變量,局部變量,外部變量有著額外的處理方式

如果一個函數中定義了與外部名稱相同的變量,在函數內部如何能夠獲得外部定義的變量呢?在其他語言中,我們都知道局部變量會覆蓋掉同名的外部變量。而在python中雖然也是這個邏輯,但是他提供了 3個函數來使得我們能夠獲得不同作用域中定義的同名的變量值。

globals()獲取所有全局變量值

locals()獲取所有局部變量值

nonlocals()獲取所有外部變量值(因為python是支持函數嵌套的,內部函數如果想要獲得外部函數局部變量的值可以使用這個)

在局部變量中獲取全局變量中同名變量

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> a = 234
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 234}
>>> def s():
...  a = 'hello'
...  print(locals())
...
>>> s()
{'a': 'hello'}
>>> def u():
...  a = 'world'
...  c = globals()['a']
...  print(c)
...
>>> u()
234

如上面代碼顯示的,在函數u()中a的值是‘world'而在全局變量中a的值是234,函數s()中局部變量a的值是'hello'通過globals()[變量名]就可以獲得全局變量中同名的變量的值。

局部改變上段代碼中同名的全局變量值

?
1
2
3
4
5
6
7
8
>>> def e():
...  a = 'sdf'
...  globals()['a'] = a
...
>>> e()
>>> a
'sdf'
>>>

以上這篇python基礎入門必看操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本不卡免免费观看 | 午夜小视频免费 | 四虎影视黄色 | 国内精品91久久久久 | 欧美又硬又粗又长又大 | chinese真实incest| 色色色色网站 | 好姑娘在线完整版视频 | 俄罗斯精品bbw | 天色综合 | mmkk在线看片| 日本在线小视频 | 男人含玉势出嫁束器 | 99久久国产综合精麻豆 | 3p文两男一女办公室高h | 女学生被老师调教在教室 | 欧美日韩成人在线视频 | 亚洲人和日本人hd | 欧美不卡一区二区三区 | 精品亚洲麻豆1区2区3区 | 精品图区 | 成人嗯啊视频在线观看 | 黄动漫车车好快的车车双女主 | 国产卡一卡二卡3卡乱码免费 | 成年人免费看的视频 | 和岳m的小说 | 秘书小说阿蛮 | 国产精品免费_区二区三区观看 | 欧产日产国产精品专区 | 色多多视频在线 | 午夜宅男网 | 精品国产品香蕉在线观看 | 欧美灰丝袜丝交nylons | 大陆国产精品视频 | 色老板在线免费视频 | 精品国产原创在线观看视频 | 国产a毛片在线 | 华人在线视频 | 欧美影院一区二区三区 | 欧美三茎同入 | 美尻在线 |