缺省参数的例子: >>> def foo(debug=1): 'determine if in debug mode with default argument' if debug: print 'in debug mode' print 'done'
>>> foo() in debug mode done >>> foo(0) done
3)Classes 类仅仅是保护静态数据成员或函数声明的容器,其静态数据成员或函数声明则称为类属性。 类提供了创建实际对象的blueprints,创建的实际对象称为类的实例。函数在类中称为方法。 声明类: class class_name[(base_classes_if_any)]: "optional documentation string" static_member_declarations method_declarations 类声明使用class关键字。如声明子类,那么其超类或基类应该在圆括号中给出。 >>> class FooClass: 'my very first class: FooClass' version = 0.1 # class (data) attribute def __init__(self, nm='John Doe'): 'constructor' self.name = nm # class instance (data) attribute print 'Created a class instance for', nm def showname(self): 'display instance attribute and class name' print 'Your name is', self.name print 'My name is', self.__class__ # full class name def showver(self): 'display class(static) attribute' print self.version # references FooClass.version def addMe2Me(self, x): # does not use 'self' 'apply + operation to argument' return (x+x)
>>> foo1 = FooClass() Created a class instance for John Doe >>> foo1.showver() 0.1 >>> print foo1.addMe2Me(5) 10 >>> print foo1.addMe2Me('xyz') xyzxyz >>> foo1.showname() Your name is John Doe My name is __main__.FooClass >>> foo2 = FooClass('Jane Smith') Created a class instance for Jane Smith >>> foo2.showname() Your name is Jane Smith My name is __main__.FooClass