python 面向對象相對別的語言來說缺少兩個功能:
1、python不具備重載,重載是指在同一個類中,使得方法有相同的名稱,但是有不同的參數列表,但由于python函數具有強大的參數處理功能,因此這不是一個問題。
2、python不存在強制數據隱私的機制,不過若想創建屬性(實例變量或方法)時在屬性名前以兩個下劃線引導,python就會阻止無心的訪問,因此可以認為是私有的。
如果一個方法是預定義的特殊方法,則應該在方法名前后加上雙下劃線,例如__sub__()和__add__()。
一、自定義類
1、方法一
class className:
suite
2、方法二
class className(base_class):
suite
二、屬性與方法
import math
class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y
def __eq__(self,other):
return self.x == other.x and self.x == other.y
def distance_from_origin(self):
return math.hypot(self.x,self.y)
def __str__(self):
return '({0.x},{0.y})'.format(self)
a = Point(1,2)
b = Point(2,2)
b.distance_from_origin()
Point.distance_from_origin(b)
a == b
str(a)
可預定義的比較方法如下:
默認情況下,自定義類的所有實例都是可哈希運算的,因此,可對其調用hash(),也可以將其作為字典的鍵,或存儲在集合中。但是如果重新實現了__eq__(),實例就不再是可哈希運算的了。
為了避免不適當的比較,可以使用如下三種方法:
使用斷言
assert isintance(object,Class),'object is not in the Class'
產生TypeError異常
if not isinstance(object,Class):
raise TypeError('object is not in the Class')
返回NotImplemented
if not isinstance(object,Class):
return NotImplement-ented
如果返回了NotImplemented,Python就會嘗試調用other.__eq__(self)來查看object是否支持與Class類的比較,如果也沒有類似的方法,Python將放棄搜索,并產生TypeError異常。
內置的isinstance()函數以一個對象與一個類為參數,如果該對象屬于該類(或類元組中的某個類),或屬于給定類的基類,就返回True
使用super()
使用super()函數可以使用基類的方法
def __init__(self,x,y,radius):
super().__init__(x,y)
self.radius = radius
在使用super()時,可以不用寫self參數。
使用特性進行屬性存取控制
一些方法返回一個單獨的值,從用戶的角度講,可以將方法可以當做數據屬性使用。以下是一個實例
class Circle(object):
def __init__(self,radius):
self.radius = radius
def area(self):
return self.radius * 2
area = property(area)
c = Circle(4)
c.area
或可寫為
class Circle(object):
def __init__(self,radius):
self.radius = radius
@property
def area(self):
return self.radius * 2
c = Circle(4)
c.area
提供了一種驗證數據有效性的方法
class Circle(object):
def __init__(self,x,y,radius):
self.radius = radius
self.x = x
self.y = y
def area(self):
return self.radius * 2
area = property(area)
@property
def radius(self):
return self.__radius
@radius.setter
def radius(self,radius):
assert radius > 0,"radius must be nonzero and non-negative"
self.__radius = radius
c = Circle(1,-2,4)
c.area
希望與廣大網友互動??
點此進行留言吧!