面向对象编程
封装
继承
多态
封装
继承
class SchoolMember:
def __init__(self, name, age):
self.name = name
self.age = age
print ' %s ' % self.name
def tell(self):
print 'Name:"%s" Age:"%s"' % (self.name,self.age),
class Teacher(SchoolMember):
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line#
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
多态
在python运行过程中,参数被传递过来之前并不知道参数的类型,虽然python中的方法也是后期绑定,但是和Java中多态的后期绑定却是不同的,java中的后期绑定至少知道对象的类型,而python中就不知道参数的类型。
模块
import math
match.floor(32.9) #模块.函数
from match import sqrt #多个函数导入可以用逗号隔开,可以使用as设置别名
sqrt(9) #使用from模块import函数后,可以直接使用函数,除非真的需要这种形式,否则还是使用上面的标准形式
import会完成以下三个操作:
创建新的名称空间(namespace),该名称空间中拥有输入模块中定义的所有对象;
执行模块中的代码;
创建该名称空间的变量名。
__name__模块的应用:当一个模块被第一次输入的时候,这个模块的主块将被运行
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
#!/usr/bin/python
# Filename: backup_ver2.py
import os
import time
# 1. The files and directories to be backed up arespecified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin'] # If you are using Windows, use source =[r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backupdirectory
target_dir = '/mnt/e/backup/' # Remember to change thisto what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory inthe main directory
today = target_dir + time.strftime('%Y%m%d') # The current time is the name of the zip archivenow = time.strftime('%H%M%S')
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today)
# make directory
print 'Successfully created directory', today
# The name of the zip file
target = today + os.sep + now + '.zip'
# 5. We use the zip command (in Unix/Linux) to put thefiles in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ''.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
os.sep变量的用法——这会根据你的操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使我们的程序具有移植性,可以在上述这些系统下工作。
类
类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。
init方法
通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性初始化绑上去
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去:
bart = Student('Bart Simpson', 59)
bart.name
'Bart Simpson'
bart.score
59
和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。除此之外,类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数和关键字参数。
# When subclassing immutable built-in types like numbers and strings, and occasionally in other situations, the static method __new__ comes in handy. __new__ is the first step in instance construction, invoked before __init__. The __new__ method is called with the class as its first argument; its responsibility is to return a new instance of that class.
class CocaCola:
formula = ['caffeine','sugar','water','soda']
def drink(self): #这里的self是下面实例化的那个对象
print 'Energy!'
coke = CocaCola()
coke.drink() # 即与CocaCola.drink(coke)是等价的
__new__方法
创建新实例调用的方法
__del__方法
当实例消逝的时候,就会调用__del__方法,可以使用del语句指定它的运行
上下文管理协议
with语句支持在另一个称为上下文管理协议的对象的控制下执行一系列语句,语法如下
with context [as var]:
statements
执行with语句时就会调用__enter__()方法,只要控制流离开with语句相关的语句块,就会立即调用__exit__()方法。exit()方法接受当前的异常的类型、值和跟踪作为参数
__enter__(self)
__exit__(self,type,value,tb)
Decorator装饰器
函数、方法或类定义的前面可以使用一个 特殊符号,称为装饰器,其目的是修改定义后面行为。装饰器使用@符号表示,必须放在单独的行上并且位于对应的函数、方法或类之前
class foo(object):
@staticmethod
def bar():
pass