首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python property疑惑,该怎么处理

2012-02-05 
python property疑惑1:class filepro(object):def __init__(self,val):self._valval...2:class filepro(o

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
>>>

热点排行