读书人

python property疑惑,该怎么处理

发布时间: 2012-02-05 12:07:15 作者: rapoo

python property疑惑
1:class filepro(object):
def __init__(self,val):
self._val=val
...
2:class filepro(object):
def __init__(self,val):
self.val=val
....

为什么第一个可以返回一个异域数值。
如果使用第二就返回AttributeError 异常呢?
在网上查了一下,说 _val是property私有成员,难道是指定property的?
为什么在其它OOP定义就没有这个问题呢?



[解决办法]
LZ说的是带双下划线的:

Python code
>>> class filepro(object):...     def __init__(self,val):...         self.__val=val...        >>> f = filepro(100)>>> f.__valTraceback (most recent call last):  File "<interactive input>", line 1, in <module>AttributeError: 'filepro' object has no attribute '__val'>>>
[解决办法]
严格来说,python class 没有完全的private,
就算是双下划的话,也可以写,


"mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger."


mangling name here is

__val in filepro
become
_filepro__val


>>> class filepro(object):
... def __init__(self,val):
... self.__val=val
... def get_val(self):
... return self.__val
...
>>> f = filepro(100)
>>> f.get_val()
100
>>> f._filepro__val = 200
>>> f.get_val()
200
>>>

读书人网 >perl python

热点推荐