python基礎(chǔ)之入門必看操作
這里提供在使用python進行開發(fā)中常使用到的方法技巧,如有不對歡迎批評指正。
要點:開發(fā)中類、變量特性查詢,類型就是類,斷言的使用,深淺復(fù)制判斷等
python腳本文件是使用UTF-8編碼的,所以在發(fā)現(xiàn)中文字符出現(xiàn)亂碼時應(yīng)當(dāng)考慮是否文本文件采用UTF-8編碼。
如果想指定不同的編碼需要在源碼文件中開頭處添加這樣的注釋:
# -*- coding: utf-8 -*-
如果python在linux和unix系統(tǒng)中運行,需要在源碼的第一行添加:
#!/usr/bin/python3
如何獲取python中各個模塊,變量,類等的內(nèi)容呢?
python中關(guān)于幫組的查詢可以通過變量__all__,__dict__,函數(shù)help(),dir()來獲取。
如果__all__在類,模塊中定義,一般包含著外部可以調(diào)用的特性,如果定義了沒有賦值,會自動使用非下劃線開頭的特性填充。如果沒有參數(shù)__all__python會提示AttributeError屬性錯誤。
__dict__一般會給出類或者模塊中定義的特性(包括屬性和方法),是以字典的形式輸出的使用元組來表示參數(shù)和參數(shù)值(參數(shù),參數(shù)值或者描述)
list的__dict__查看
>>> 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 >>> 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()就可以了,當(dāng)然很多時候也需要help()查看詳細的文檔(其實就是__doc__中的內(nèi)容):
list使用help()查看
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 --
如果我們現(xiàn)在創(chuàng)建了一個對象 a = list(),現(xiàn)在想要獲取對象a有什么特性方法,也是使用dir()和help()。
在這里需要強調(diào)的是,dir()和help()的強大之處不僅僅可以查閱類,還可以我們定義的變量。這樣我們在編碼過程中能夠獲得更多的內(nèi)容。
a=1中變量a含有方法的查找
>>> 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__查看原來定義設(shè)計的內(nèi)容外,可以使用很多已經(jīng)定義的特性來獲取更多信息:
獲取變量類型和對象類型的方法:
通過__class__查詢變量和類類型
>>> 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'>
通過上面的代碼我們發(fā)現(xiàn),如果class為type其實這個本身就是一個類的定義,如果是其他的則是對象。
你想過沒有,在python中基本的變量也是對象?
在一般語言中,我們的類型都分為整型,浮點型,字符串等等。但是在python這些類型其實都是類的形式定義的,而類也是繼承了頂級超類的。
使用__class__查看類型,__bases__查看超類
>>> 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__ () >>>
發(fā)現(xiàn)沒有,我們使用的類型其實都是類,除了bool繼承了類int,其他的都是繼承超類object。而object類沒有超類。應(yīng)該說,type是一個類型類!當(dāng)然None類型是NoneType,而NoneType卻不是類,這是說None是個空值。
type類中含有的內(nèi)容和object類中含有的內(nèi)容
>>> 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()可以讓我們看清變量之間的隱藏關(guān)系!
我們都知道,python從在使用上有著弱類型的便捷性。當(dāng)然在python中,相同數(shù)值的變量只有一個!這是為什么呢?這是因為他們都是指向同一個內(nèi)存地址,可以將這些變量想象成他們存放的是一個個內(nèi)存地址,我們對他們的賦值不過是將他們指向的內(nèi)存地址做了改變??!
從指針的角度理解python是很有幫助的。變量本身存放的是指針,如果你這個能夠理解了,那么關(guān)于python的變量和內(nèi)存回收機制就能夠很好理解并運用了。
A is B 操作的作用是判斷A是否是B,如果為真,則說明A與B是同一個對象,如果為假,則說明A與B不是同一個對象。
id(A) 操作的作用是判斷A在內(nèi)存中的id序列號。
下面我們來詳細說明下python中的相關(guān)現(xiàn)象:
1.python中A和B雖然是同一個對象,但是當(dāng)對A賦值之后,A與B再是同一個對象,因為python中的賦值是將A所所指向的地址改成了另一個對象的地址,這時候與B中的地址不一樣,B地址所致的對象的值不會收到A賦值影響。
2.python中同一個對象所具有的id可能是不同的,因為在沒有指向該地址的變量時,python內(nèi)存自動清理會清理掉這個對象。再次使用到具有相同數(shù)值的對象可能是在前一個對象自動清理之后創(chuàng)建的新對象。
針對第一個情況我們首先通過對True和False和數(shù)字來確定哪些值對象的id是系統(tǒng)自帶的,即便這些值對象不被變量使用python內(nèi)存清理也不會清理這些對象!
通過id來判斷數(shù)值和布爾值中的值對象是否是系統(tǒng)自帶的對象
>>> 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
你會發(fā)現(xiàn)數(shù)字-5到256是連續(xù)的,他們相鄰的id值相差是32,意思是他們是32表示的數(shù)值。id返回的值就是他們在python中邏輯內(nèi)存地址的值,在不同python進程中這些相同值對象返回的id值是一致的。而小于-5或者大于256的數(shù)值,小數(shù),超過單個字符的字符串都是python在用戶使用時創(chuàng)建的值對象,在不同的python進程中相同的值的id是不同的!其他值在不使用時有的就會被python內(nèi)存清理程序清理掉釋放內(nèi)存!

當(dāng)然,python中還有很多對象、類、函數(shù)等是python自創(chuàng)建的不會因為不使用而被內(nèi)存清理程序清理掉。比如 int,None,dict,list。
不夠值得一提的是 None is None是返回True 。并且id(None)的返回值是1538983120。這說明與其他腳本(比如javascript)不一樣,None是空值,是一個唯一的空值對象,程序中所有的None都是相等的。都是同一個內(nèi)存地址中存放的值。
很多情況下,我們想判斷兩個變量是否指向同一個內(nèi)存地址塊存放的值,可以使用is來判斷。
python中對于全局變量,局部變量,外部變量有著額外的處理方式
如果一個函數(shù)中定義了與外部名稱相同的變量,在函數(shù)內(nèi)部如何能夠獲得外部定義的變量呢?在其他語言中,我們都知道局部變量會覆蓋掉同名的外部變量。而在python中雖然也是這個邏輯,但是他提供了 3個函數(shù)來使得我們能夠獲得不同作用域中定義的同名的變量值。
globals()獲取所有全局變量值
locals()獲取所有局部變量值
nonlocals()獲取所有外部變量值(因為python是支持函數(shù)嵌套的,內(nèi)部函數(shù)如果想要獲得外部函數(shù)局部變量的值可以使用這個)
在局部變量中獲取全局變量中同名變量
>>> 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
如上面代碼顯示的,在函數(shù)u()中a的值是‘world'而在全局變量中a的值是234,函數(shù)s()中局部變量a的值是'hello'通過globals()[變量名]就可以獲得全局變量中同名的變量的值。
局部改變上段代碼中同名的全局變量值
>>> def e(): ... a = 'sdf' ... globals()['a'] = a ... >>> e() >>> a 'sdf' >>>
以上這篇python基礎(chǔ)之入門必看操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python Scrapy實戰(zhàn)之古詩文網(wǎng)的爬取
本文將利用Python中Scrapy框架,實現(xiàn)爬取古詩文網(wǎng)上的詩詞數(shù)據(jù),具體包括詩詞的標(biāo)題信息。文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-05-05
基于python?win32setpixel?api?實現(xiàn)計算機圖形學(xué)相關(guān)操作(推薦)
這篇文章主要介紹了基于python?win32setpixel?api?實現(xiàn)計算機圖形學(xué)相關(guān)操作,這次的主要分為2個主要模塊,一個是實現(xiàn)畫線,畫圓的算法,還有填充的算法,以及裁剪的算法,需要的朋友可以參考下2021-12-12
PyCharm Python Console中文輸出亂碼問題及解決
這篇文章主要介紹了PyCharm Python Console中文輸出亂碼問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Python實現(xiàn)帶參數(shù)的用戶驗證功能裝飾器示例
這篇文章主要介紹了Python實現(xiàn)帶參數(shù)的用戶驗證功能裝飾器,結(jié)合實例形式分析了Python用戶驗證裝飾器具體定義及使用技巧,需要的朋友可以參考下2018-12-12
解決django xadmin主題不顯示和只顯示bootstrap2的問題
這篇文章主要介紹了解決django xadmin主題不顯示和只顯示bootstrap2的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03

