Code: Select all
class A:
def __init__(self, n):
self._n = n
self._top = -1
@property
def n(self):
return self._n
@property
def top(self):
return self._top
def increase(self):
self._top += 1
Eigenschaft Setzer -Methode
einstellen lässt
Code: Select all
a = A(7)
a.top
Out[25]: -1
a.increase()
a.top
Out[27]: 0
Code: Select all
AttributeError: property 'top' of 'A' object has no setter
< /code>
, was erwartet wird. Jetzt möchte ich diese Logik in einen Deskriptor < /p>
neu gestaltenclass ReadOnly:
def __init__(self):
self._name = None
def __set_name__(self, owner, name):
self._name = name
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self._name]
def __set__(self, instance, value):
raise AttributeError("Can't set attribute")
def __delete__(self, instance):
raise AttributeError("Can't delete attribute")
class A:
n = ReadOnly()
top = ReadOnly()
def __init__(self, n):
self.n = n
self.top = -1
def increase(self):
self.top += 1
< /code>
Nun, das funktioniert nicht. Ich kann die Klasse A
Code: Select all
class Stack:
S = ReadOnly()
n = ReadOnly()
top = ReadOnly()
def __init__(self, n):
self._S = [None] * n
self._n = n
self._top = -1 # python offset 1
< /code>
Jetzt kann ich Self.top nicht mehr ändern < /p>
>>> s = Stack(4)
>>> s.S
[None, None, None, None]
< /code>
Noch kann ich S < /p>
ändern>>> s.S = [1, 3] # not allowed anymore. Great!
But I can still change an element in the list
>>> s.S[3] = 3
[None, None, None, 3]