您的位置:首页 > 编程语言 > Python开发

Python基础之函数

2017-05-04 10:47 405 查看
三元运算

三元运算(三目运算),是对简单的条件语句的缩写。

# 书写格式

result = 值1 if 条件 else 值2

# 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量


基本数据类型补充

set

set集合,是一个无序且不重复的元素集合

class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set,添加元素

This has no effect if the element is already present.
"""
pass

def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. 清除内容"""
pass

def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. 浅拷贝  """
pass

def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set. A中存在,B中不存在

(i.e. all elements that are in this set but not the others.)
"""
pass

def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
pass

def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member.

If the element is not a member, do nothing. 移除指定元素,不存在不保错
"""
pass

def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set. 交集

(i.e. all elements that are in both sets.)
"""
pass

def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another.  取交集并更更新到A中 """
pass

def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
pass

def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set.  是否是子序列"""
pass

def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. 是否是父序列"""
pass

def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty. 移除元素
"""
pass

def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
"""
pass

def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.  对称差集

(i.e. all elements that are in exactly one of the sets.)
"""
pass

def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
pass

def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set.  并集

(i.e. all elements that are in either set.)
"""
pass

def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. 更新 """
pass


深浅拷贝

一、数字和字符串

对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

import copy
# ######### 数字、字符串 #########
n1 = 123
# n1 = "i am alex age 10"
print(id(n1))
# ## 赋值 ##
n2 = n1
print(id(n2))
# ## 浅拷贝 ##
n2 = copy.copy(n1)
print(id(n2))

# ## 深拷贝 ##
n3 = copy.deepcopy(n1)
print(id(n3))


class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer.

encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False).

errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict".

newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'.  It works as follows:

* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.

* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.

If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass

def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass

def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass

def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass

def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass

def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass

def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass

def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass

def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass

def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass

def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass

def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass

def write(self, *args, **kwargs): # real signature unknown
写内容
pass

def __getstate__(self, *args, **kwargs): # real signature unknown
pass

def __init__(self, *args, **kwargs): # real signature unknown
pass

@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object.  See help(type) for accurate signature. """
pass

def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass

def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass

buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default


3.x
三、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:

...


如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
pass


lambda表达式

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

# 普通条件语句
if 1 == 1:
name = 'jeff'
else:
name = 'jason'

# 三元运算
name = 'jeff' if 1 == 1 else 'jason'


对于简单的函数,也存在一种简便的表示方式,即:lambda表达式

# ###################### 普通函数 ######################
# 定义函数(普通方式)
def func(arg):
return arg + 1

# 执行函数
result = func(123)

# ###################### lambda ######################

# 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1

# 执行函数
result = my_lambda(123)


递归

利用函数编写如下数列:

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...

def func(arg1,arg2):
if arg1 == 0:
print arg1, arg2
arg3 = arg1 + arg2
print arg3
func(arg2, arg3)

func(0,1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: