面向過程的編程思維是:按照處理流程,每一步需要做什么?用哪些函數可以解決?嚴格按照流程來把事情完成就ok了。這個在實際的應用中貌似還是多一點,因為簡單,要求低一點。
相對來說,面向過程的編程就更抽象一點。考慮問題的出發點不再是問題解決的流程,而是everything is a object,對象有變量和方法,而解決問題的方式是:哪些對象需要具有哪些屬性和方法?如何通過各個對象之間的信息傳遞來解決問題?
#代碼清單-1 面向過程的程序示例:打印姓名和成績
std1={'name':'Michael','score':98} std2={'name':'Bob','score':81}
def print_score(std): print '%s: %s' % (std['name'], std['score'])
print_score(std1) print_score(std2)
#代碼清單-2 面向對象的程序示例:打印姓名和成績
class Student(object): def __init__(self,name,score): self.name=name self.score=score def print_score(self): print '%s: %s' %(self.name, self.score)
bart =Student('Bart Simpson',59) lisa=Student('Lisa Simpson',87) bart.print_score() lisa.print_score()
1.類和實例
類是對象的抽象,比如籠統地提到“學生”,就是一個類,指的是學生那一類人群。而對象呢,則是類的一個實例化、具體化,比如一個叫“張三”的高中生就是“學生”這個類的一個實例,也就是“學生”類的一個對象。
每個對象都擁有相同的方法,但各自的數據則不盡相同。
1.1類的定義和實例化
下面的示例先定義了一個類,然后實例化了一個對象出來。
**#代碼清單3-1: 定義類** class Student(object): def __init__(self, name, score): self.name = name self.score = score
**#代碼清單3-2: 實例化** bart=Student('Bart Sipson',59) bart.name #'Bart Sipson' bart.score #59
1.2 數據封裝
繼續,在定義類的同時,定義、封裝了兩個新的方法:打印成績和等級。
''' 定義類 class Student(object): def __init__(self, name, score): self.name = name self.score = score '''新增方法 def print_score(self): print '%s: %s' % (self.name,self.score) def get_grade(self): if self.score>=90: return 'A' elif self.score>=60: return 'B' else: return 'C'
''' 調用封裝的方法 bart.print_score() # Bart Sipson: 59 bart.get_grade() # 'C'
2.訪問限制
以 __
(雙下劃線)開頭的變量表示私有變量,外部無法訪問。
''' 定義類,設置私有變量 class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print '%s: %s' % (self.__name,self.__score) def get_grade(self): if self.__score>=90: return 'A' elif self.__score>=60: return 'B' else: return 'C'
'''對象無法引用私有變量 bart = Student('Bart Simpson', 98) bart.__name '''報錯信息: Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute '__name'
可以使用get方法和set方法來獲取和修改變量的值。那么問題來了, 如果不把變量設置為私有變量,也可以通過重新賦值的方式來修改值啊,那為什么要單獨搞一個set方法呢?
因為set方法可以做參數檢查,防止傳入無效的參數。
'''定義類''' class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print '%s: %s' % (self.__name,self.__score) def get_grade(self): if self.__score>=90: return 'A' elif self.__score>=60: return 'B' else: return 'C' '''set與get方法''' def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self,score): if 0 <= score <= 100: self.__score=score else: raise ValueError('bad score') def set_name(self,name): self.__name=name
bart=Student('Bart Sipson',59) bart.get_score() #59 bart.set_score(63) bart.get_score() #63
3.繼承和多態
子類可以繼承父類的所有方法,同時也可以自行定義屬于自己的方法。
class Animal(object): def run(self): print 'Animal is running...'
class Dog(Animal): pass
class Cat(Animal): pass
dog=Dog() dog.run()
cat=Cat() cat.run()
class Dog(Animal): def run(self): print 'Dog is running...' def eat(self): print 'Eating meat...'
class Cat(Animal): def run(self): print 'Cat is running...'
dog=Dog() dog.run()
cat=Cat() cat.run()
判斷一個變量是否是某個類型可以用isinstance()
判斷:
a = list() # a是list類型 b = Animal() # b是Animal類型 c = Dog() # c是Dog類型
isinstance(a, list) #True isinstance(b, Animal) #True isinstance(c, Dog) #True isinstance(c, Animal) #True
理解多態,抓住“開閉”原則:對擴展開放:允許新增Animal子類;對修改封閉:不需要修改依賴Animal類型的run_twice()等函數。
下面的例子中,Dog,Cat,Tortoise都是Animal的子類,調用run_twice方法時,會自動調用屬于自己的run方法。
def run_twice(animal): animal.run() animal.run()
run_twice(Animal()) run_twice(Dog()) run_twice(Cat())
class Tortoise(Animal): def run(self): print 'Tortoise is running slowly...'
run_twice(Tortoise())
4.獲取對象信息
來判斷對象類型,使用type()
函數:
'''基本類型'''
type(123)
<type 'int'>
type('str')
<type 'str'>
type(None)
<type 'NoneType'>
'''函數或者類'''
type(abs)
type(a)
type(123)==type(456)
type('abc')==type('123')
type('abc')==type(123)
import types
type('abc')==types.StringType
type(u'abc')==types.UnicodeType
type([])==types.ListType
type(str)==types.TypeType
type(int)==type(str)==types.TypeType
使用isinstance()
a = Animal()
d = Dog()
h = Husky()
isinstance(h, Husky)
isinstance(h, Dog)
isinstance(h, Animal)
isinstance(d, Dog) and isinstance(d, Animal)
isinstance(d, Husky)
isinstance('a', str)
isinstance(u'a', unicode)
isinstance('a', unicode)
isinstance('a', (str, unicode))
isinstance(u'a', (str, unicode))
isinstance(u'a', basestring)
使用dir
dir('ABC')
len('ABC')
3
'ABC'.len()
3
class MyObject(object):
def len(self):
return 100
obj = MyObject()
len(obj)
'ABC'.lower()
class MyObject(object):
def init(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
hasattr(obj, 'x') # 有屬性'x'嗎?
True
obj.x
9
hasattr(obj, 'y') # 有屬性'y'嗎?
False
setattr(obj, 'y', 19) # 設置一個屬性'y'
hasattr(obj, 'y') # 有屬性'y'嗎?
True
getattr(obj, 'y') # 獲取屬性'y'
19
obj.y # 獲取屬性'y'
19
getattr(obj, 'z') # 獲取屬性'z'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
getattr(obj, 'z', 404) # 獲取屬性'z',如果不存在,返回默認值404
404
hasattr(obj, 'power') # 有屬性'power'嗎?
True
getattr(obj, 'power') # 獲取屬性'power'
<bound method MyObject.power of <main.MyObject object at 0x108ca35d0>>
fn = getattr(obj, 'power') # 獲取屬性'power'并賦值到變量fn
fn # fn指向obj.power
<bound method MyObject.power of <main.MyObject object at 0x108ca35d0>>
fn() # 調用fn()與調用obj.power()是一樣的
81