1. 程式人生 > >【Python】【面向對象】

【Python】【面向對象】

cor 常量 lam 字節流 ack eth rfi numeric 活性


# 【【面向對象】】
#【訪問限制】
#如果要讓內部屬性不被外部訪問,可加雙下劃線,編程私有變量。只有內部可以訪問,外部不能訪問。
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‘,66)
#print(bart.__name) #AttributeError: ‘Student‘ object has no attribute ‘__name‘
#如果想讓外部代碼獲取name score 可以如下
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_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‘)
#【註意】__name__是特殊變量,可直接訪問,不是private變量,所以,不能用__name__這樣的變量名。
# 一個下劃線,外部可以訪問,但是按照約定俗成,遇到這樣的,就當成是私有的
# 雙下劃線不能直接訪問的原因,python解釋器對外把__name改成了_Student__name,所以仍然可通過_Student__name來訪問__name變量
print(bart._Student__name) #Bart Simpson
# 但是強烈建議不要這麽做,因為不同版本的python解釋器,可能會把__name改成不同的變量名。
#註意下面錯誤寫法
bart = Student(‘Bart Simpson‘,66)
print(bart.get_name()) #Bart Simpson
bart.__name = ‘New Name‘
print(bart.__name) #New Name 【註意】此時的__name和類內部的__name不是一回事,內部的已經被python解釋器自動改成了_Student__name,外部代碼給bart對象新增了一個__name變量
print(bart.get_name()) #Bart Simpson

# 【繼承&多態】
#繼承可以把父類所有功能直接拿過來,這樣就不必從零做起。子類只需要新增自己的方法,也可以把父類不適合的方法覆蓋重寫。
#動態語言的鴨子類型決定了繼承不像靜態語言那樣是必須的。


#【獲取對象信息】
# 1 使用type() 判斷基本數據類型可直接寫int str 等。 如果要判斷是否是函數,可 用types 模塊中定義的常量。
import types
def fn():
pass

print (type(fn) == types.FunctionType) #True
print (type(abs) == types.BuiltinFunctionType) #True
print (type(lambda x:x) == types.LambdaType) #True
print (type(x for x in range(10)) == types.GeneratorType) #True

# 2 使用isinstance() 可用type() 的都可用isinstance() 但可用isinstance()的不一定就能用type()代替
print (isinstance(‘12‘,str)) #True
print (isinstance((lambda x:x),types.LambdaType)) #True

class Animal(object):
def run(self):
print (‘animal is running..‘)
class Dog(Animal):
def run(self):
print (‘dog is running..‘)
class Hushy(Dog):
def run(self):
print (‘hushy is running..‘)

a = Animal()
d = Dog()
h = Hushy()
print (type(d) == Dog) #True
print (type(d) == Animal) #False
print (isinstance(d,Dog)) #True
print (isinstance(d,Animal)) #True
print (isinstance(h,Animal)) #True
print (isinstance(d,Hushy)) #False
#還可以判斷一個變量是否是某些類型中的一種。
print (isinstance([1,2,3],(list,tuple))) #True

#【小結】總是優先使用isinstance(), 可以將指定類型及其子類"一網打盡"

# 3 使用dir() 獲取一個對象所有屬性和方法。
print (dir(‘ABC‘)) #[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
#僅僅是把屬性和方法列出來是不夠的,配合getattr() setattr() hasattr() ,可以直接操作一個對象的狀態
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()

print (hasattr(obj,‘x‘)) #True
print (obj.x) #9
print (hasattr(obj,‘y‘)) #False
setattr(obj,‘y‘,19)
print (hasattr(obj,‘y‘)) #True
print (getattr(obj,‘y‘)) #19
print (obj.y) #19
#如果試圖獲取不存在的屬性,拋出AttributeError
#print (getattr(obj,‘z‘)) #AttributeError: ‘MyObject‘ object has no attribute ‘z‘
#可傳一個default參數,如果屬性不存在,就返回默認值
print (getattr(obj,‘z‘,404)) #404
#也可以獲得對象的方法
print (hasattr(obj,‘power‘)) #True
print (getattr(obj,‘power‘)) #<bound method MyObject.power of <__main__.MyObject object at 0x102a36470>>
#獲取屬性power並賦值到變量fn
fn = getattr(obj,‘power‘)
print (fn) #<bound method MyObject.power of <__main__.MyObject object at 0x1022364a8>>
print (fn()) #81

‘‘‘
獲取對象信息

閱讀: 214832
當我們拿到一個對象的引用時,如何知道這個對象是什麽類型、有哪些方法呢?

使用type()

首先,我們來判斷對象類型,使用type()函數:

基本類型都可以用type()判斷:

>>> type(123)
<class ‘int‘>
>>> type(‘str‘)
<class ‘str‘>
>>> type(None)
<type(None) ‘NoneType‘>
如果一個變量指向函數或者類,也可以用type()判斷:

>>> type(abs)
<class ‘builtin_function_or_method‘>
>>> type(a)
<class ‘__main__.Animal‘>
但是type()函數返回的是什麽類型呢?它返回對應的Class類型。如果我們要在if語句中判斷,就需要比較兩個變量的type類型是否相同:

>>> type(123)==type(456)
True
>>> type(123)==int
True
>>> type(‘abc‘)==type(‘123‘)
True
>>> type(‘abc‘)==str
True
>>> type(‘abc‘)==type(123)
False
判斷基本數據類型可以直接寫int,str等,但如果要判斷一個對象是否是函數怎麽辦?可以使用types模塊中定義的常量:

>>> import types
>>> def fn():
... pass
...
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(lambda x: x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True
使用isinstance()

對於class的繼承關系來說,使用type()就很不方便。我們要判斷class的類型,可以使用isinstance()函數。

我們回顧上次的例子,如果繼承關系是:

object -> Animal -> Dog -> Husky
那麽,isinstance()就可以告訴我們,一個對象是否是某種類型。先創建3種類型的對象:

>>> a = Animal()
>>> d = Dog()
>>> h = Husky()
然後,判斷:

>>> isinstance(h, Husky)
True
沒有問題,因為h變量指向的就是Husky對象。

再判斷:

>>> isinstance(h, Dog)
True
h雖然自身是Husky類型,但由於Husky是從Dog繼承下來的,所以,h也還是Dog類型。換句話說,isinstance()判斷的是一個對象是否是該類型本身,或者位於該類型的父繼承鏈上。

因此,我們可以確信,h還是Animal類型:

>>> isinstance(h, Animal)
True
同理,實際類型是Dog的d也是Animal類型:

>>> isinstance(d, Dog) and isinstance(d, Animal)
True
但是,d不是Husky類型:

>>> isinstance(d, Husky)
False
能用type()判斷的基本類型也可以用isinstance()判斷:

>>> isinstance(‘a‘, str)
True
>>> isinstance(123, int)
True
>>> isinstance(b‘a‘, bytes)
True
並且還可以判斷一個變量是否是某些類型中的一種,比如下面的代碼就可以判斷是否是list或者tuple:

>>> isinstance([1, 2, 3], (list, tuple))
True
>>> isinstance((1, 2, 3), (list, tuple))
True
總是優先使用isinstance()判斷類型,可以將指定類型及其子類“一網打盡”。
使用dir()

如果要獲得一個對象的所有屬性和方法,可以使用dir()函數,它返回一個包含字符串的list,比如,獲得一個str對象的所有屬性和方法:

>>> dir(‘ABC‘)
[‘__add__‘, ‘__class__‘,..., ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘,..., ‘zfill‘]
類似__xxx__的屬性和方法在Python中都是有特殊用途的,比如__len__方法返回長度。在Python中,如果你調用len()函數試圖獲取一個對象的長度,實際上,在len()函數內部,它自動去調用該對象的__len__()方法,所以,下面的代碼是等價的:

>>> len(‘ABC‘)
3
>>> ‘ABC‘.__len__()
3
我們自己寫的類,如果也想用len(myObj)的話,就自己寫一個__len__()方法:

>>> class MyDog(object):
... def __len__(self):
... return 100
...
>>> dog = MyDog()
>>> len(dog)
100
剩下的都是普通屬性或方法,比如lower()返回小寫的字符串:

>>> ‘ABC‘.lower()
‘abc‘
僅僅把屬性和方法列出來是不夠的,配合getattr()、setattr()以及hasattr(),我們可以直接操作一個對象的狀態:

>>> 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
如果試圖獲取不存在的屬性,會拋出AttributeError的錯誤:

>>> getattr(obj, ‘z‘) # 獲取屬性‘z‘
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘MyObject‘ object has no attribute ‘z‘
可以傳入一個default參數,如果屬性不存在,就返回默認值:

>>> 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 0x10077a6a0>>
>>> fn = getattr(obj, ‘power‘) # 獲取屬性‘power‘並賦值到變量fn
>>> fn # fn指向obj.power
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
>>> fn() # 調用fn()與調用obj.power()是一樣的
81
小結

通過內置的一系列函數,我們可以對任意一個Python對象進行剖析,拿到其內部的數據。要註意的是,只有在不知道對象信息的時候,我們才會去獲取對象信息。如果可以直接寫:

sum = obj.x + obj.y
就不要寫:

sum = getattr(obj, ‘x‘) + getattr(obj, ‘y‘)
一個正確的用法的例子如下:

def readImage(fp):
if hasattr(fp, ‘read‘):
return readData(fp)
return None
假設我們希望從文件流fp中讀取圖像,我們首先要判斷該fp對象是否存在read方法,如果存在,則該對象是一個流,如果不存在,則無法讀取。hasattr()就派上了用場。

請註意,在Python這類動態語言中,根據鴨子類型,有read()方法,不代表該fp對象就是一個文件流,它也可能是網絡流,也可能是內存中的一個字節流,但只要read()方法返回的是有效的圖像數據,就不影響讀取圖像的功能。

‘‘‘

# 【實例屬性& 類屬性】
#可以為實例綁定任何屬性和方法,這就是動態語言的靈活性。

# 【__slots__】
# 正常情況下,當我們定義了一個class,創建了一個class實例後,我們可以為該實例綁定任何屬性和方法,這就是動態語言的靈活性。
class Student(object):
pass
s = Student()
s.name = ‘Michael‘
print(s.name)
#還可以給 實例綁定一個方法
def set_age(self,age):
self.age = age
from types import MethodType
s.set_age = MethodType(set_age,s)
s.set_age(25)
print(s.age) #25
#但是,給一個實例綁定的方法,對另一個實例是不起作用的
s2 = Student()
#s2.set_age(46) #AttributeError: ‘Student‘ object has no attribute ‘set_age‘
#為了給所有實例di

































【Python】【面向對象】