10分钟学会Python[1]
2008-10-23 13:27:13 来源:WEB开发网函数使用def关键字。可选参数在必须参数之后出现,并且可以被赋一默认值。对命名参数而言,参数名参数名被赋一个值。函数可以返回一个元组(打开元组你就可以实现返回多个值)。Lanbda函数是个特例,它由一个表达式构成。参数使用引用传递,但是可变类型(元组,列表,数字,字符串等等)不能被改变。举例如下:
# arg2 and arg3 are optional, they have default values
8. 类
# if one is not passed (100 and "test", respectively).
def myfunction(arg1, arg2 = 100, arg3 = "test"):
return arg3, arg2, arg1
>>>ret1, ret2, ret3 = myfunction("Argument 1", arg3 = "Named argument")
# Using "print" with multiple values prints them all, separated by a space.
>>> print ret1, ret2, ret3
Named argument 100 Argument 1
# Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
Python部分支持类的多重继承。私有变量和方法可以使用至少两个"_"开始并且至少一个"_"结束来声明,比如"__spam"(这只是约定,语言中并没有强制规定)。我们可以给类的实例赋任意的变量。请看下例:
class MyClass:
common = 10
def __init__(self):
self.myvariable = 3
def myfunction(self, arg1, arg2):
return self.myvariable
# This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will create a new one on the class
# instance and assign the value to that.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50
# This class inherits from MyClass. Multiple
# inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
def __init__(self, arg1):
self.myvariable = 3
print arg1
>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10
- ››python操作sharepoint对象模型
- ››Python 2.6.2的.pyc文件格式
- ››Python 2.6.2的字节码指令集一览
- ››Python 测试框架: 用 Python 测试框架简化测试
- ››Python 测试框架: 寻找要测试的模块
- ››Python的class系统
- ››Python 和 LDAP
- ››python图形处理库PIL(Python Image Library)
- ››Python图形图像处理库的介绍之Image模块
- ››Python和Google AppEngine开发基于Google架构的应...
- ››Python 3 初探,第 1 部分: Python 3 的新特性
- ››python源码中中文注释的处理
更多精彩
赞助商链接