类属性与方法
类的私有属性
__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
类的方法
在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定使用 self。
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods。
实例
类的私有属性实例如下:
实例(Python 3.0+)
#!/usr/bin/python3classJustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 defcount(self): self.__secretCount += 1 self.publicCount += 1 print(self.__secretCount)counter = JustCounter()counter.count()counter.count()print(counter.publicCount)print(counter.__secretCount) # 报错,实例不能访问私有变量
执行以上程序输出结果为:
1
2
2
Traceback(most recent call last):
File"test.py", line 16,in
print(counter.__secretCount) # 报错,实例不能访问私有变量
AttributeError:'JustCounter'object has no attribute '__secretCount'