[Answer]-Delaying / Calling Class Attributes Set Equal to Methods

1👍

Using properties, you can have article1.author actually call self.lookup_author and return it.

output:

John Doe
<Author: John Doe>

bob
<Author: bob>

code:

class Article(object):
    def __init__(self, id, author):
        self.id = id
        self.__author = None

    def lookup_author(self):
        return "John Doe"


    def __str__(self):
        return "<Author: {}>".format(self.author)

    @property
    def author(self):
        if self.__author is None:
            self.__author = self.lookup_author()
        return self.__author

    @author.setter
    def author(self,name):
        self.__author = name

article1 = Article(1, 'John Doe')
print "\n", article1.author
print article1

article1.author = 'bob'
print "\n", article1.author
print article1

For some reason, if needed, __author doesn’t have to even exist until the getter is used. You can do that using exceptions.

Leave a comment