Python has written the following code:
class Test:
def __init__(self):
self.hello = 0
@property
def test(self):
return self.hello
@test.setter
det test(self, hello):
self.hello = hello
if __name__ == '__main__':
t = Test()
t.test = 1
t.test2 = 2 # I want to make an error here.
I keep making typos in the method name, but I keep making mistakes because there is no error in test2. I want to make an error when I count a function that doesn't exist in the first place. Is there any way to make me throw an error?
(We have confirmed that an AttributeError occurs if you call a getter immediately without substituting the value. I wonder if I should check this first and then proceed with the setter.)
python
Hello.
It's best not to make a typo, but you can use However, as you can see above, If you need to use the 'old style' class, you can override __slots__
to declare the properties you want to use in advance. p>
class Test(object):
__slots__ = ['hello']
def __init__(self):
self.hello = 0
@property
def test(self):
return self.hello
@test.setter
def test(self, hello):
self.hello = hello
if __name__ == '__main__':
t = Test()
t.test = 1
t.test2 = 2
__slot__
requires a 'new style' class, such as class A(object)
, which is available from Python 2.2.__setattr__
as follows.class Test:
def __setattr__(self, name, value):
allowed = ('hello', 'test')
if name in allowed:
self.__dict__[name] = value
else:
raise AttributeError('No attribute: %s' % name)
def __init__(self):
self.hello = 0
@property
def test(self):
return self.hello
@test.setter
def test(self, hello):
self.hello = hello
if __name__ == '__main__':
t = Test()
t.test = 1
t.test2 = 2
© 2024 OneMinuteCode. All rights reserved.