这概念和c语言中的函数呀,java中的方法概念其实是一样的。
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
比如说,java中的System.out.println(....)也就是一个方法,python中的print(.....),这些是各个语言的内置函数,我们也可以自定义函数,被叫做:用户自定义函数。
1.函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。
2.任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
3.函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
4.函数内容以冒号起始,并且缩进。
5.return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
比如说我们现在需要定义一个函数,该函数功能是把传入的元组进行进行排序
#定义函数
def println(paramters):
"函数说明:打印传入的字符串到标准显示设备上,每次输出空一行"
print(paramters + "\n")
return
#函数调用
println("My name is ckmike...")
println("hello!")
println("what's the fuck!")
我们在前一篇中写的猜数字游戏小程序中代码为例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#预设猜数值
realnumber = 35
#猜测数字次数
times = 3
#循环进行程序输入判断
while times > 0:
target = int(input("请输入数字:"))
#判断是否与目标数值相等
if target == realnumber:
print("bingo!")
break
elif target > realnumber:
print("输入的值比目标值大!")
else:
print("输入数值比目标数值小!")
times -= 1
else:
print("三次机会已经用完!")
从上面的代码,我们知道realnumber变量、times变量,我们知道不管java还是c#,都是在变量前必须限定这个变量类型,因为他们都是强类型语言( 目前是这样,后面发展也许会有改变也不一定。)。而python中的变量是没有类型的,python是弱类型语言。
我们再看下面代码:
a = [12,13,14]
a = "CkMike"
前一行a指向了一个list的列表,后一句则指向了一个字符串。
在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。
不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变a的值,相当于新生成了a。
可变类型:变量赋值 a=[1,2,3,4] 后再赋值 a[2]=5 则是将 list la 的第三个元素值更改,本身a没有动,只是其内部的一部分值被修改了。
python 函数的参数传递:
不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。
可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响
不可变类型参数演示:
def plus(num):
num = 100
a = 30
plus(a)
print(a)
结果输出还是30
可变类型参数演示:
# 可写函数说明
def changelist( mylist ):
"修改传入的列表"
mylist.append(1);
mylist.append(2);
mylist.append(3);
print("函数内取值:", mylist)
return
target = ['a','b','c','d']
changelist(target)
print(target)
#可写函数说明
def printinfo( name, *boxes, age = 21, sex = '男' ):
"打印任何传入的字符串"
print("Name: ", name)
print("Age ", age)
print("Sex ", sex)
print("购买了如下包:")
#遍历输出boxes的名字
for box in boxes:
print(box)
return
#调用
printinfo("ckgirl","LV","Prada","KUQI", age= 25, sex="女")
总结:
1.参数可以给定默认值,给定默认值,则该参数为选填
2.选填参数必须放置在最后面
3.不定长参数必须放置定长必填参数后面且放置在选填参数前面
4.传递参数时,可以使用形参关键字传递指定的参数,可以不关心先后顺序,但要注意不定长参数位置一定要准守3规则,不管是定义还是调用传递参数时。
python 使用 lambda 来创建匿名函数。
lambda只是一个表达式,函数体比def简单很多。
lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
lambda函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。
虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
# 调用sum函数
print("相加后的值为 : ", sum( 10, 20 ))
print("相加后的值为 : ", sum( 20, 20 ))
全局变量、局部变量
定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
total = 0; # 这是一个全局变量
# 可写函数说明
def sum(arg1, arg2):
# 返回2个参数的和."
total = arg1 + arg2; # total在这里是局部变量.
print("函数内是局部变量 : ", total)
return total;
# 调用sum函数
sum(10, 20);
print("函数外是全局变量 : ", total)
Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。模块让你能够有逻辑地组织你的 Python 代码段。把相关的代码分配到一个模块里能让你的代码更好用,更易懂。模块能定义函数,类和变量,模块里也能包含可执行的代码。
# 引入time模块
import time
# 调用模块中函数,获取当前时间戳
print(time.time())
我们可以自行去查看time.py这个模块代码,如下:
# encoding: utf-8
# module time
# from (built-in)
# by generator 1.145
"""
This module provides various functions to manipulate time values.
There are two standard representations of time. One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).
The other representation is a tuple of 9 integers giving local time.
The tuple items are:
year (including century, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
Variables:
timezone -- difference in seconds between UTC and local standard time
altzone -- difference in seconds between UTC and local DST time
daylight -- whether local time should reflect DST
tzname -- tuple of (standard time zone name, DST time zone name)
Functions:
time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
"""
# no imports
# Variables with simple values
altzone = -32400
daylight = 0
timezone = -28800
_STRUCT_TM_ITEMS = 11
# functions
def asctime(p_tuple=None): # real signature unknown; restored from __doc__
"""
asctime([tuple]) -> string
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used.
"""
return ""
def clock(): # real signature unknown; restored from __doc__
"""
clock() -> floating point number
Return the CPU time or real time since the start of the process or since
the first call to clock(). This has as much precision as the system
records.
"""
return 0.0
def ctime(seconds=None): # known case of time.ctime
"""
ctime(seconds) -> string
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used.
"""
return ""
def get_clock_info(name): # real signature unknown; restored from __doc__
"""
get_clock_info(name: str) -> dict
Get information of the specified clock.
"""
return {}
def gmtime(seconds=None): # real signature unknown; restored from __doc__
"""
gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
GMT). When 'seconds' is not passed in, convert the current time instead.
If the platform supports the tm_gmtoff and tm_zone, they are available as
attributes only.
"""
pass
def localtime(seconds=None): # real signature unknown; restored from __doc__
"""
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead.
"""
pass
def mktime(p_tuple): # real signature unknown; restored from __doc__
"""
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
Note that mktime(gmtime(0)) will not generally return zero for most
time zones; instead the returned value will either be equal to that
of the timezone or altzone attributes on the time module.
"""
return 0.0
def monotonic(): # real signature unknown; restored from __doc__
"""
monotonic() -> float
Monotonic clock, cannot go backward.
"""
return 0.0
def perf_counter(): # real signature unknown; restored from __doc__
"""
perf_counter() -> float
Performance counter for benchmarking.
"""
return 0.0
def process_time(): # real signature unknown; restored from __doc__
"""
process_time() -> float
Process time for profiling: sum of the kernel and user-space CPU time.
"""
return 0.0
def sleep(seconds): # real signature unknown; restored from __doc__
"""
sleep(seconds)
Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
"""
pass
def strftime(format, p_tuple=None): # real signature unknown; restored from __doc__
"""
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
"""
return ""
def strptime(string, format): # real signature unknown; restored from __doc__
"""
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
"""
return struct_time
def time(): # real signature unknown; restored from __doc__
"""
time() -> floating point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
"""
return 0.0
# classes
class struct_time(tuple):
"""
The time value as returned by gmtime(), localtime(), and strptime(), and
accepted by asctime(), mktime() and strftime(). May be considered as a
sequence of 9 integers.
Note that several fields' values are not the same as those defined by
the C language standard for struct tm. For example, the value of the
field tm_year is the actual year, not year - 1900. See individual
fields' descriptions for details.
"""
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 __reduce__(self, *args, **kwargs): # real signature unknown
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
tm_gmtoff = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""offset from UTC in seconds"""
tm_hour = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""hours, range [0, 23]"""
tm_isdst = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""1 if summer time is in effect, 0 if not, and -1 if unknown"""
tm_mday = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""day of month, range [1, 31]"""
tm_min = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""minutes, range [0, 59]"""
tm_mon = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""month of year, range [1, 12]"""
tm_sec = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""seconds, range [0, 61])"""
tm_wday = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""day of week, range [0, 6], Monday is 0"""
tm_yday = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""day of year, range [1, 366]"""
tm_year = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""year, for example, 1993"""
tm_zone = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""abbreviation of timezone name"""
n_fields = 11
n_sequence_fields = 9
n_unnamed_fields = 0
class __loader__(object):
"""
Meta path import for built-in modules.
All methods are either class or static methods to avoid the need to
instantiate the class.
"""
@classmethod
def create_module(cls, *args, **kwargs): # real signature unknown
""" Create a built-in module """
pass
@classmethod
def exec_module(cls, *args, **kwargs): # real signature unknown
""" Exec a built-in module """
pass
@classmethod
def find_module(cls, *args, **kwargs): # real signature unknown
"""
Find the built-in module.
If 'path' is ever specified then the search is considered a failure.
This method is deprecated. Use find_spec() instead.
"""
pass
@classmethod
def find_spec(cls, *args, **kwargs): # real signature unknown
pass
@classmethod
def get_code(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have code objects. """
pass
@classmethod
def get_source(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have source code. """
pass
@classmethod
def is_package(cls, *args, **kwargs): # real signature unknown
""" Return False as built-in modules are never packages. """
pass
@classmethod
def load_module(cls, *args, **kwargs): # real signature unknown
"""
Load the specified module into sys.modules and return it.
This method is deprecated. Use loader.exec_module instead.
"""
pass
def module_repr(module): # reliably restored by inspect
"""
Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
# variables with complex values
tzname = (
'Öйú±ê׼ʱ¼ä',
'ÖйúÏÄÁîʱ',
)
__spec__ = None # (!) real value is ''
总结:
上面用import 后面接模块名的方式导入整个模块,模块会导入一次,且只会导入一次,不管你import了几次该模块。
但有时候我只想引入模块中的某一个函数式该如何导入呢?
from 模块名 import 目标对象
备注:
from 模块名 import * 等效于import 模块名
这个其实很简单,就跟前端中的import模块是一样的,相比较与java和C#类似于从一个命名空间中引入下列的对应类,比如说:
// 导入指定的对象
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
// 这就把util包下的所有对象都导入了
import java.util.*;
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。
简单来说,包就是文件夹,但该文件夹下必须存在 init.py 文件, 该文件的内容可以为空。init.py 用于标识当前文件夹是一个包。
这个你可以用pycharm开发工具创建一个试一下。
可以根据自己定义内容。
init.py文件内容如下:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
print('作为主程序运行')
else:
print('初始化')
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。