首页 >后端开发 >Python教程 >python基础入门级操作总结

python基础入门级操作总结

巴扎黑
巴扎黑原创
2017-08-13 14:53:391399浏览

下面小编就为大家带来一篇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