设为首页 加入收藏

TOP

Python常用的方法定义
2014-11-24 07:46:15 来源: 作者: 【 】 浏览:0
Tags:Python 常用 方法 定义

Python常用的方法定义:


方法在OOP中会经常用到,减少代码的冗余,作为一门面向对象的语言,Python自然也有自己的方法定义。那么怎样在Python中定义一个方法呢,很简洁的方法:define functionname()


调用的时候直接使用这个方法名就可以了,functionname(),就可以了,当然在方法定义的时候一样可以定义它的输入参数,例如:define functionname(yourname,myname),在调用的时候传入参数即可。


__author__="Alex"
__date__ ="$2011-2-17 10:39:27$"
if __name__ == "__main__":
print "Hello";
#define a function
def welcome():
print("Welcome to my python class")
# define a function by arg
def welcome_bylevel( name, level ):
print ( 'Welcome ' + name + ' to the program =)' )
print ( 'We will try some things out.' )
if level == 'pro': print ( 'Be patient, I am beginner.' )
print ('')
welcome()
welcome_bylevel( 'Alex', 'beginner' )
welcome_bylevel( 'Viki', 'pro' )


Console Output:


Hello
Welcome to my python class
Welcome Alex to the program =)
We will try some things out.
Welcome Viki to the program =)
We will try some things out.
Be patient, I am beginner.


动态调用


在Python代码中方法的参数如果不确定为多少个的时候,可以用*arg来表示,例如:


__author__="Alex"
__date__ ="$2011-2-17 10:39:27$"
if __name__ == "__main__":
print "Hello";
#define a function
def welcome(name,level="beginner",*skill):
print("Hello, "+name)
if level!="beginner":
print("We will show something out");
else:
print("I am beginner of python")
if len(skill)>0:
for i in skill:
print('you are good at:'+i)
welcome("Viki")
welcome('Alex',"pro","Python","Linux")


控制台输出:


Hello
Hello, Viki
I am beginner of python
Hello, Alex
We will show something out
you are good at:Python
you are good at:Linux


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android NDK-r5 成功运行编译运行.. 下一篇Python 的Hello World!

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·PostgreSQL 索引 - (2025-12-25 22:20:43)
·MySQL Node.js 连接 (2025-12-25 22:20:41)
·SQL 撤销索引、表以 (2025-12-25 22:20:38)
·Linux系统简介 (2025-12-25 21:55:25)
·Linux安装MySQL过程 (2025-12-25 21:55:22)