类属性与方法

  • 类的私有属性
__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)