首頁 >後端開發 >Python教學 >python之入門基礎操作(必看)

python之入門基礎操作(必看)

黄舟
黄舟原創
2017-07-26 15:46:131350瀏覽

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

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

要點:開發中類別、變數特性查詢,類型就是類,斷言的使用,深淺複製判斷等

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

如果想要指定不同的編碼需要在原始碼檔案中開頭處新增這樣的註解:


#
# -*- coding: utf-8 -*-

如果python在linux和unix系統中運行,需要在原始碼的第一行新增:


#!/usr/bin/python3

如何取得python中各個模組,變數,類別等的內容呢?

python中關於幫組的查詢可以透過變數__all__,__dict__,函數help(),dir()來取得。

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

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

list的__dict__查看


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

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

list使用dir()查看


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

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

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&#39;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含有方法的查找


>>> a=1
>>> dir(a)
[&#39;__abs__&#39;, &#39;__add__&#39;, &#39;__and__&#39;, &#39;__bool__&#39;, &#39;__ceil__&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__pmod__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__float__&#39;, &#39;__floor__&#39;, &#39;__floorp__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__index__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__int__&#39;, &#39;__invert__&#39;, &#39;__le__&#39;, &#39;__lshift__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__neg__&#39;, &#39;__new__&#39;, &#39;__or__&#39;, &#39;__pos__&#39;, &#39;__pow__&#39;, &#39;__radd__&#39;, &#39;__rand__&#39;, &#39;__rpmod__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rfloorp__&#39;, &#39;__rlshift__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__ror__&#39;, &#39;__round__&#39;, &#39;__rpow__&#39;, &#39;__rrshift__&#39;, &#39;__rshift__&#39;, &#39;__rsub__&#39;, &#39;__rtruep__&#39;, &#39;__rxor__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__sub__&#39;, &#39;__subclasshook__&#39;, &#39;__truep__&#39;, &#39;__trunc__&#39;, &#39;__xor__&#39;, &#39;bit_length&#39;, &#39;conjugate&#39;, &#39;denominator&#39;, &#39;from_bytes&#39;, &#39;imag&#39;, &#39;numerator&#39;, &#39;real&#39;, &#39;to_bytes&#39;]
>>> 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 &#39;+&#39; or &#39;-&#39; 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(&#39;0b100&#39;, 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__查詢變數和類別類型


#

>>> a =1
>>> a.__class__
<class &#39;int&#39;>
>>> b = 1.0
>>> b.__class__
<class &#39;float&#39;>
>>> c = &#39;&#39;
>>> c.__class__
<class &#39;str&#39;>
>>> d = list()
>>> d.__class__
<class &#39;list&#39;>
>>> e = tuple()
>>> e.__class__
<class &#39;tuple&#39;>
>>> f = dict()
>>> f.__class__
<class &#39;dict&#39;>
>>> list.__class__
<class &#39;type&#39;>
>>> dict.__class__
<class &#39;type&#39;>
>>> tuple.__class__
<class &#39;type&#39;>
>>> object.__class__
<class &#39;type&#39;>
>>> None.__class__
<class &#39;NoneType&#39;>

透過上面的程式碼我們發現,如果class為type其實這個本身就是一個類別的定義,如果是其他的則是物件。

你想過沒有,python中基本的變數也是物件?

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

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


>>> a = 1
>>> a.__class__
<class &#39;int&#39;>
>>> int.__class__
<class &#39;type&#39;>
>>> str.__class__
<class &#39;type&#39;>
>>> bool.__class__
<class &#39;type&#39;>
>>> list.__class__
<class &#39;type&#39;>
>>> dict.__class__
<class &#39;type&#39;>
>>> tuple.__class__
<class &#39;type&#39;>
>>> type.__class__
<class &#39;type&#39;>
>>> object.__class__
<class &#39;type&#39;>
>>> type.__bases__
(<class &#39;object&#39;>,)
>>> int.__bases__
(<class &#39;object&#39;>,)
>>> str.__bases__
(<class &#39;object&#39;>,)
>>> bool.__bases__
(<class &#39;int&#39;>,)
>>> float.__bases__
(<class &#39;object&#39;>,)
>>> object.__bases__
()
>>>

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

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


#

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

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来判断数值和布尔值中的值对象是否是系统自带的对象


>>> 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自创建的不会因为不使用而被内存清理程序清理掉。比如 int,None,dict,list。

不够值得一提的是 None is None是返回True 。并且id(None)的返回值是1538983120。这说明与其他脚本(比如javascript)不一样,None是空值,是一个唯一的空值对象,程序中所有的None都是相等的。都是同一个内存地址中存放的值。

很多情况下,我们想判断两个变量是否指向同一个内存地址块存放的值,可以使用is来判断。

python中对于全局变量,局部变量,外部变量有着额外的处理方式

如果一个函数中定义了与外部名称相同的变量,在函数内部如何能够获得外部定义的变量呢?在其他语言中,我们都知道局部变量会覆盖掉同名的外部变量。而在python中虽然也是这个逻辑,但是他提供了 3个函数来使得我们能够获得不同作用域中定义的同名的变量值。

globals()获取所有全局变量值

locals()获取所有局部变量值

nonlocals()获取所有外部变量值(因为python是支持函数嵌套的,内部函数如果想要获得外部函数局部变量的值可以使用这个)

在局部变量中获取全局变量中同名变量


>>> a = 234
>>> globals()
{&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: <class &#39;_frozen_importlib.BuiltinImporter&#39;>, &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: <module &#39;builtins&#39; (built-in)>, &#39;a&#39;: 234}
>>> def s():
...  a = &#39;hello&#39;
...  print(locals())
...
>>> s()
{&#39;a&#39;: &#39;hello&#39;}
>>> def u():
...  a = &#39;world&#39;
...  c = globals()[&#39;a&#39;]
...  print(c)
...
>>> u()
234

如上面代码显示的,在函数u()中a的值是‘world'而在全局变量中a的值是234,函数s()中局部变量a的值是'hello'通过globals()[变量名]就可以获得全局变量中同名的变量的值。

局部改变上段代码中同名的全局变量值


>>> def e():
...  a = &#39;sdf&#39;
...  globals()[&#39;a&#39;] = a
...
>>> e()
>>> a
&#39;sdf&#39;
>>>

以上是python之入門基礎操作(必看)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn