Python (2.7) newbie here. What I want to do is have a reference to an instance of a class return a given property as the ‘default’ without having to specify that property. I want to do this because the vast majority of the time I refer to an instance, it is to access this one property.
For example, let’s say I have a couple of classes to describes a book:
class book:
def __init__(self):
self.title = ''
self.author = ''
self.page = {}
class page:
def __init__(self):
self.text = ''
self.length = 0
I create an instance and fill it with the contents of a book like so:
...
war_and_peace = book()
page_count = 0
for page in pages: #Let's say pages is a list of strings each of a page of the book
pagenum += 1
war_and_peace.page[pagenum] = page
Now in the remainder of the program, 99.9% of the time I reference the text of the pages. So to make my life a little easier, I would like to be able to reference a page using:
if 'Anna' in war_and_peace[15]:
...
instead of
if 'Anna' in war_and_peace.page[15].text:
...
How might I go about this? (Sorry if this has been answered; I am probably using the wrong search terms!)
Thanks!
A
__getitem__override onbookwill give you this: