[Tutor] Get/Set/Attribute Accessors in Python?

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Dec 6 05:42:29 CET 2012


On 05/12/2012 16:58, Steven D'Aprano wrote:
>
> And here is how it should be written in Python:
>
> class Example(object):
>      def __init__(self, value):
>          self.x = value
>
>
> instance = Example(42)
> print instance.x  # gives 42
> instance.setx(23)
>
>

And introduce error handling while we're at it? Should we consider a 
CutAndPasteError in Python? :)

c:\Users\Mark\MyPython>type mytest.py
class Example(object):
     def __init__(self, value):
         self.x = value


instance = Example(42)
print(instance.x)  # gives 42
instance.setx(23)
c:\Users\Mark\MyPython>mytest.py
42
Traceback (most recent call last):
   File "C:\Users\Mark\MyPython\mytest.py", line 8, in <module>
     instance.setx(23)
AttributeError: 'Example' object has no attribute 'setx'


-- 
Cheers.

Mark Lawrence.



More information about the Tutor mailing list