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