python只读属性怎么设置_Python只读属性

有一种方法可以避免这样的假设all users are consenting adults, and thus are responsible for using

things correctly themselves.

请参阅下面的我的更新

使用@property非常冗长,例如:class AClassWithManyAttributes:

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

def a(self):

return self._a

@property

def b(self):

return self._b

@property

def c(self):

return self._c

# you get this ... it's long

使用No underscore: it's a public variable.

One underscore: it's a protected variable.

Two underscores: it's a private variable.

除了最后一个,这是一个惯例。如果你真的努力了,你仍然可以用双下划线访问变量。

那我们该怎么办?我们是否放弃在Python中使用只读属性?

瞧!read_only_properties装饰工来救人!@read_only_properties('readonly', 'forbidden')

class MyClass(object):

def __init__(self, a, b, c):

self.readonly = a

self.forbidden = b

self.ok = c

m = MyClass(1, 2, 3)

m.ok = 4

# we can re-assign a value to m.ok

# read only access to m.readonly is OK

print(m.ok, m.readonly)

print("This worked...")

# this will explode, and raise AttributeError

m.forbidden = 4

你问:Where is read_only_properties coming from?def read_only_properties(*attrs):

def class_rebuilder(cls):

"The class decorator"

class NewClass(cls):

"This is the overwritten class"

def __setattr__(self, name, value):

if name not in attrs:

pass

elif name not in self.__dict__:

pass

else:

raise AttributeError("Can't modify {}".format(name))

super().__setattr__(name, value)

return NewClass

return class_rebuilder

更新

我从来没想到这个答案会受到如此多的关注。令人惊讶的是。这鼓励我创建一个可以使用的包。$ pip install read-only-properties

在python shell中:In [1]: from rop import read_only_properties

In [2]: @read_only_properties('a')

...: class 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'

---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

in ()

----> 1 f.a = 'boom'

/home/oznt/.virtualenvs/tracker/lib/python3.5/site-packages/rop.py in __setattr__(self, name, value)

116 pass

117 else:

--> 118 raise AttributeError("Can't touch {}".format(name))

119

120 super().__setattr__(name, value)

AttributeError: Can't touch a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值