There is no foolproof way of protecting your code from outside use in Python.
But if you follow the conventions in this course, you won’t have to.
Protect With Underscores
Most Python programmers see a method or attribute prefixed with _ and leave it alone. That goes doubly so for methods or attributes with a double underscore preceding but not trailing (__avoided, not avoided).
class Protected:
__name = 'Security'
def __method(self):
return self.__name
Testing
>>> prot = Protected()
>>> prot.__name
ERROR!
>>> prot.__method()
ERROR!
A double underscore will protect your class attribute and methods from usage. There is, however, a workaround to use them.
>>> prot._Protected__method()
'Security'
>>> prot._Protected__name
'Security'
Protect With @property
class Circle:
def __init__(self, diameter):
self.diameter = diameter
@property
def radius(self):
return self.diameter / 2
Testing
>>> small = Circle(10)
>>> print(small.diameter)
10
>>> print(small.radius)
5.0
@property
Notice we didn’t follow up the method radius
with parentheses; the @property
decorator makes a method behave like an attribute. That’s what a property is, except, it is protected from being set from outside the class.
>>> small.radius = 10
ERROR!
To work around this, we can provide what is known as a setter that sets the attribute/property.
class Circle:
def __init__(self, diameter):
self.diameter = diameter
@property
def radius(self):
return self.diameter / 2
@radius.setter
def radius(self, radius):
self.diameter = radius * 2
@radius.setter
A setter method radius
must have the same name as the property, and it must be decorated with @radius.setter
Testing
>>> small.radius = 10
>>> print(small.diameter)
20