Python 定义私有属性:
Python没有类似于Java的private关键字, 但也可以为类定义私有属性. 只需将属性命名变为以__开头, 例如 __field.
示例代码:
class Vector2D(object):
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
self.xx = x
self.yy = y
def get_x(self):
return self.__x # 内部访问
if __name__ == "__main__":
v = Vector2D(3, 4)
print v.__dict__
print v._Vector2D__x, v.get_x()# 但是可以通过v._Vector2D__x 在外部访问
v.__x # 外部访问12345678910111213
输出:
{'yy': 4, 'xx': 3, '_Vector2D__x': 3.0, '_Vector2D__y': 4.0}
3.0 3.0
Traceback (most recent call last):
...
v.__x
AttributeError: 'Vector2D' object has no attribute '__x'
从上面的例子可以看出:
1. __field被编译器重命名为_className__field
2. 在class外部不能访问obj.__field, 但在class内部可以
3. 但是, 这只能防止无意间的调用, 不能防止恶意调用, 用Fluent Python的话来讲, 这是一种safety device, not security device, 用国语来讲, 就是防君子不防xx, 因为可以通过obj._className__field在外部访问obj的私有__field.
类的方法
在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数
私有的类方法
__private_method 两个下划线开头,声明该方法为私有方法,不能在类地外部调用
在类的内部调用slef.__private_methods
类的专有方法:
__init__ 构造函数,在生成对象时调用
__del__ 析构函数,释放对象时使用
__repr__ 打印,转换
__setitem__按照索引赋值
__getitem__按照索引获取值
__len__获得长度
__cmp__比较运算
__call__函数调用
__add__加运算
__sub__减运算
__mul__乘运算
__div__除运算
__mod__求余运算
__pow__称方
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
继承类定义:
1.单继承
1 2 3 4 5 |
|
2.类的多重继承
1 2 |
|