• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 252
  • Last Modified:

Python, referencing a sub-class

Hello experts,

I am having a problem that I hope there is an solution to.

I have a base class called Document. I then have few sub-classes of Document (Book, Magazine, ...). My problem lies in the fact that a Book has an author attribute but a Magazine doesn't. So when I do:

documents = bookModel.Document.objects.all()

for document in documents:
    print document.author

I get nothing since the base class doesn't have an author attribute.

Do these instanced of a base class not know they are really  implemented as sub-classes ?

I hope I am being clear enough
0
mannsi
Asked:
mannsi
  • 2
1 Solution
 
HonorGodCommented:
Q: Do base classes "know" that they have been extended (have descendants)?
A: No.

You might choose to define an author attribute for documents, and default the value to None until a descendant needs this.  But this isn't normally done.

You could use something like this though, to see if the object instance has/contains the "author" attribute...

if 'author' in dir( document ) :
  # do something with the document.author ...

But that really isn't very object oriented.
0
 
HonorGodCommented:
Thanks for the grade & points.

Good luck & Happy New Year.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now