類屬性與方法

  • 類的私有屬性
__private_attrs:兩個劃線開頭,聲明該屬性爲私有,不能在類地外部使用或直接訪問,在類內部的方法中使用時 self._private_attrs
class JustCounter:
    __secretCount = 0  # 私有變量
    publicCount = 0  # 公開變量


    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)

    def __count1(self):
        print ("私有的方法")

counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
counter.__count1()            #報錯,私有方法,不能在類外部調用,只能在類的內部調用
print (counter._secretCount)  #報錯,由於是私有的變量,counter沒法訪問

#輸出
1
Traceback (most recent call last):
2
2
  File "F:/PythonWrokPlace/ss.py", line 200, in <module>
    counter.__count1()            #報錯,私有方法,不能在類外部調用,只能在類的內部調用
AttributeError: JustCounter instance has no attribute '__count1'
  • 類的方法
在類的內部,使用 def 關鍵字來定義一個方法,與通常函數定義不一樣,類的方法必須需包含參數 self,且第一個參數,self表明的是類的實例。
self 的名字並非規定死的,也能夠使用 this,可是最好仍是按照約定用 self

  • 類的私有方法
__private_method:兩個下劃線開頭,聲明該方法爲私有方法,只能在類的內部調用,不能在裏的外部調用。self.__private_methods

  • 類的專有方法
_int_:構造函數,在生成對象時條用
_del_:析構函數,釋放對象時使用
_repr_:打印,轉換
_setitem_:按照索引獲取值
_len_:獲取長度
_cmp_:比較運算
_call_:函數調用
_add_:加運算
_sub_:減運算
_mul_:乘運算
_div_:除元算
_mod_:求餘運算
_pow_:乘方

  • 運算符重載
重載是在同一個類中的兩個或兩個以上的方法,擁有相同的方法名,可是參數卻不相同,方法體也不相同
Python一樣支持運算符重載,我麼能夠對類的專有方法進行重載
class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)


v1 = Vector(2, 10)
v2 = Vector(5, -2)
print (v1 + v2)

#輸出
Vector(7,8)
相關文章
相關標籤/搜索