- 类的私有属性
__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'
1
class JustCounter:
2
__secretCount = 0 # 私有变量
3
publicCount = 0 # 公开变量
4
5
6
def count(self):
7
self.__secretCount += 1
8
self.publicCount += 1
9
print (self.__secretCount)
10
11
def __count1(self):
12
print ("私有的方法")
13
14
counter = JustCounter()
15
counter.count()
16
counter.count()
17
print (counter.publicCount)
18
counter.__count1() #报错,私有方法,不能在类外部调用,只能在类的内部调用
19
print (counter._secretCount) #报错,因为是私有的变量,counter无法访问
20
21
#输出
22
1
23
Traceback (most recent call last):
24
2
25
2
26
File "F:/PythonWrokPlace/ss.py", line 200, in <module>
27
counter.__count1() #报错,私有方法,不能在类外部调用,只能在类的内部调用
28
AttributeError: JustCounter instance has no attribute '__count1'
29
- 类的方法
在类的内部,使用 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)
7,8
15
1
class Vector:
2
def __init__(self, a, b):
3
self.a = a
4
self.b = b
5
6
def __str__(self):
7
return 'Vector (%d, %d)' % (self.a, self.b)
8
9
def __add__(self, other):
10
return Vector(self.a + other.a, self.b + other.b)
11
12
13
v1 = Vector(2, 10)
14
v2 = Vector(5, -2)
15
print (v1 + v2)
16
17
#输出
18
Vector(7,8)