Setters Getters Properties
suggest changeFor the sake of data encapsulation, sometimes you want to have an attribute whose value comes from other attributes or, in general, whose value shall be computed at the moment. The standard way to deal with this situation is to create a method, called a getter or a setter.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
In the example above, it’s easy to see what happens if we create a new Book that contains a title and an author. If all books we’re to add to our Library have authors and titles, then we can skip the getters and setters and use the dot notation. However, suppose we have some books that do not have an author and we want to set the author to “Unknown”. Or if they have multiple authors and we plan to return a list of authors.
In this case we can create a getter and a setter for the author attribute.
class P:
def __init__(self,title,author):
self.title = title
self.setAuthor(author)
def get_author(self):
return self.author
def set_author(self, author):
if not author:
self.author = "Unknown"
else:
self.author = author
__init__ calls self.setAuthor, but the method defined here is set_author, so constructing P raises AttributeError.
This scheme is not recommended.
One reason is that there is a catch: Let’s assume we have designed our class with the public attribute and no methods. People have already used it a lot and they have written code like this:
>>> book = Book(title="Ancient Manuscript", author="Some Guy")
>>> book.author = "" #Cos Some Guy didn't write this one!
Now we have a problem. That assignment writes the author attribute directly, so a later set_author would not run. Python offers a solution to this problem called properties. A method to get properties is decorated with the @property before its header. The method that we want to function as a setter is decorated with @attributeName.setter before it.
Keeping this in mind, we now have our new updated class.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
@property
def author(self):
return self.__author
@author.setter
def author(self, author):
if not author:
self.author = "Unknown"
else:
self.author = author
Note, normally a second def with the same name replaces the first. Python does not keep two methods because they take different numbers of parameters. Here the decorators attach both functions to one property.
The setter assigns through self.author, which calls the setter again, and __author is never stored. Constructing a Book raises RecursionError before the later assignment can run:
>>> book = Book(title="Ancient Manuscript", author="Some Guy")
RecursionError: maximum recursion depth exceeded