有避免这样的假设all users are consenting adults,and thus are responsible for using的方法
things correctly themselves。
请参阅以下我的更新
@property的使用非常冗长。 例如classaclasswithmanyattributes 3360
“”refactored to properties“”
def __init__(a、b、c、d、e . )
self._a=a
self._b=b
self._c=c
self.d=d
self.e=e
@property
默认(self ) :
return self._a
@property
默认(self ) :
return self._b
@property
默认(self ) :
return self._c
# you get this . it's long
否使用underscore : it ' sapublicvariable。
一次: it ' saprotectedvariable。
two underscores 3360 it ' saprivatevariable。
除了最后一点,这是惯例。 如果你真的努力了,你可以用双下划线访问变量。
那我该怎么办? 是否要停止在Python中使用只读属性?
你看! read_only_properties装修工救人! @ read _ only _ properties (' readonly ',' forbidden ' ) )。
类别我类别(object ) :
def __init__(self,a,b,c ) :
self.readonly=a
self.forbidden=b
self.ok=c
m=my class (1,2,3 ) )。
m.ok=4
# we can re-assign a value to m.ok
# readonlyaccesstom.readonly isok
打印(m.ok,m.readonly ) )。
print('thisworked . ' )
# this will explode,and raise AttributeError
m.forbidden=4
问: where is read _ only _ propertiescomingfrom? defread_only_properties(*attrs ) :
defclass_rebuilder(cls ) :
' The class decorator '
类类(cls ) :
' This is the overwritten class '
def __setattr__(self,name,value ) :
if name not in attrs:
通过
elif name not in self._ _ dict _ _ :
通过
else:
raiseattributeerror (' can ' t modify { } '.format ) (name ) )
super ().__setattr__(name,value ) ) ) ) )。
返回新类
return class_rebuilder
更新
我没想到这个答案会这么受关注。 令人吃惊的是。 这鼓励我做一个能用的包。 $ pipinstallread-only-properties
在python shell中,in [1] : fromropimportread _ only _ properties
in [2] : @ read _ only _ properties (
.类foo :
. def __init__(self,a,b ) :
. self.a=a
. self.b=b
.
in[3]:f=foo(explodes,) ok-to-overwrite ) ) ) )。
In [4]: f.b=5
In [5]: f.a='boom '
------------- -请参阅
属性错误跟踪(mostrecentcalllast ) )。
输入() )。
---- 1 f.a='boom '
/home/oznt/. virtuale NVS/tracker/lib/python 3.5/site-packages/ROP.pyin _ _ setattr _ (self、name、name
16次通过
117 else:
- 118 raiseattributeerror (' can ' t touch { } '.format (name ) )
119
120 super ().__setattr__(name,value ) ) ) )。
AttributeError: Can't touch a