开发学院软件开发Python 10分钟学会Python[1] 阅读

10分钟学会Python[1]

 2008-10-23 13:27:13 来源:WEB开发网   
核心提示: 函数使用def关键字,可选参数在必须参数之后出现,10分钟学会Python[1](4),并且可以被赋一默认值,对命名参数而言,比如"__spam"(这只是约定,语言中并没有强制规定),参数名参数名被赋一个值,函数可以返回一个元组(打开元组你就可以实现返回多个值)

函数使用def关键字。可选参数在必须参数之后出现,并且可以被赋一默认值。对命名参数而言,参数名参数名被赋一个值。函数可以返回一个元组(打开元组你就可以实现返回多个值)。Lanbda函数是个特例,它由一个表达式构成。参数使用引用传递,但是可变类型(元组,列表,数字,字符串等等)不能被改变。举例如下:

# arg2 and arg3 are optional, they have default values
# 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
8. 类

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

上一页  1 2 3 4 

Tags:分钟 学会 Python

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接