Python 2.7 Tutorial Pt 8

Python 2.7 TutorialIn this tutorial, I continue to explain how Object Oriented Programming is used with Python 2.7. I cover some of the more complicated subjects including how to:

  • Allow the user to define an infinite number of attributes
  • Use Inheritance and what it is
  • Override Methods
  • Use Polymorphism and what it is
  • Inherit from 2 more more classes
  • Use many of the built in object methods in Python

If you don’t completely understand Object Oriented Programming after this and the first part of this tutorial Python Object Oriented Programming. Please leave a comment below and I’ll do whatever I can to explain this important subject.

Like always, a lot of code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Here is All the Code from the Video

Note: You have to insert the white space and everything will work. I could have styled it with HTML, but that would have required you to erase all of the tags. Hope this helps?

#! /usr/bin/python

__metaclass__ = type

class Animal:

__name = “No Name”
__owner = “No Owner”

def __init__(self, **kvargs): # The constructor function called when object is created
self._attributes = kvargs

# There is a function called a destructor __del__, but its best to avoid it

def set_attributes(self, key, value): # Accessor Method
self._attributes[key] = value

def get_attributes(self, key):
return self._attributes.get(key, None)

def noise(self): # self is a reference to the object
print(‘errr’) # You use self so you can access attributes of the object

def move(self):
print(‘The animal moves forward’)

def eat(self):
print(‘Crunch, crunch’)

def __hiddenMethod(self): # A hidden method
print “Hard to Find”

class Dog(Animal):

def __init__(self, **kvargs):   # Not needed unless you plan to override the super
super(Dog, self).__init__() # This wouldn’t work without the second line
self._attributes = kvargs

def noise(self):        # Overriding the Animal noise function
print(‘Woof, woof’)

class Cat(Animal):

def __init__(self, **kvargs):  # Not needed unless you plan to override the super
super(Cat, self).__init__()
self._attributes = kvargs

def noise(self):

def noise2(self):

class Dat(Cat,Dog):

def __init__(self, **kvargs):  # Not needed unless you plan to override the super
super(Dat, self).__init__()
self._attributes = kvargs

def move(self):
print(‘Chases Tail’)

def playWithAnimal(Animal): # This is polymorphism
Animal.noise() # Works even if the method isn’t in Cat because Cat is an Animal
print ‘\n’

jake = Dog(__name = ‘Jake’, __owner = ‘Paul’)
sophie = Cat(__name = ‘Sophie’, __owner = ‘Sue’)

# print sophie.__hiddenMethod() Demonstrating private methods

print issubclass(Cat, Animal) # Checks if Cat is a subclass of Animal
print Cat.__bases__           # Prints out the base class of a class
print sophie.__class__        # Prints the objects class
print sophie.__dict__         # Prints all of an objects attributes

japhie = Dat(__name = ‘Japhie’, __owner = ‘Sue’)
print japhie.get_attributes(‘__name’)

33 Responses to “Python 2.7 Tutorial Pt 8”

  1. Omar says:

    Bothering again, lol,… just to say: don’t you ever stop doing this

  2. Hi,

    Thank you for your work, helps me a lot ! I am going to go thru you other tutorials, I am looking to use MVC with Python and will try to use the bean/dao/services paradigms in order to achieve that.

  3. Eva says:

    Thanks for the wonderful tutorial. It’s very clear and informative. I have a small problem with some of the code in pt 8. get_attributes returns None when I try it.

  4. says:

    interesting, but i wish you had developed
    setting attrs with **kvargs in Animals before introducing inheritance–as it becomes difficult to parse concepts. Specifically–i am trying to set up a simlple Animals vario with **kvargs only

    class Animal:

    def __init__(self, **kvargs):
    self._attributes = kvargs

    def set_attributes(self, key, value):
    self._attributes[key] = value

    def get_attributes(self, key):
    return self._attributes.get(key, None)

    def main():
    jake = Animal(name = ‘Jake’, owner = ‘Paul’)
    print jake._attributes #ok
    print #not ok

    if __name__ == ‘__main__’: main()


  5. pjordan says:

    Sorry to see you deleted my question–i think i can restate the issue issue this way: the attributes of Animal,
    Animal.__name (=”no name”)
    Animal.__owner (=”no owner”)
    are not being addressed and continue to exist with their null values in original Animal and its derived classes. They are superceded by the dictionary attribute “._attributes” created from **kwargs. I think it would be much clearer if you deleted the attrs
    Animal.__name (=”no name”)
    Animal.__owner (=”no owner”)


    • admin says:

      I didn’t delete your question. I just can’t allow auto commenting because I’m attacked all of the time. Sorry about that.

      You make a good point and I’ll look into your ideas. I often crank these videos out with a focus on just teaching the basics and the code isn’t always optimized. I recently slowed down on quantity and now instead focus on quality.

  6. pjordan says:

    thanks for clarifying. I like the somewhat
    free form and fast style–mostly one can get it “on the rewind”. thanks

    • admin says:

      I started making the videos faster because I noticed that almost everyone else went very slow. Their videos normally were very short, so I lengthened mine. Then recently I started covering topics that nobody else has. I’m doing my best to make original videos that haven’t been done.

      The input you guys provide also dramatically influences what I do. Thanks

  7. Adhithya says:

    Your tutorials are great!!
    Thanks for it and keep posting 🙂

  8. David says:

    I have been trying to learn python for a while now and I have found your tutorials very captivating and I commend you effort.

  9. Oren says:

    Hi Derek
    Great video, you explains about automatically entering key value pairs into an attribute called _attributes. Can I add then dynamically to self. = kvargs[key]. I ask because I want them to become inherited and called by the built in function hasattr etc.


  10. Cyd says:

    I couldn’t figure out why my print statements weren’t working without parens. Then I remembered that I went and installed Python3 to work with another tutorial (not as good as this one). I assume that’s the difference?

    (I want to learn 2.7, so that I can learn Django.)

    Thanks again for this excellent series.

  11. John says:

    Liking the tutorials and appreciating the labor of your efforts.

    I have to say though, even though many are asking for more at once, part 8 was like trying to drink from a fire hose.

    Reviewing the video again… (and maybe again…)


    • admin says:

      Thank you very much. If a tutorial doesn’t click, print out the code and take notes. If you don’t understand a specific part feel free to ask questions. I’m here to help

  12. Hera says:

    Question…Why do you use a “return” statement at the end of methods that don’t return anything (ex: set_attributes(), noise())???

    • admin says:

      You don’t have to use return, but I do it out of habit. Just understand that if you don’t call return every python function returns the value None

  13. Marko says:

    Hi Derek, tell me please, can Dog class ,in this example, inherit private variables __name and __owner from Animal class, and second is there chain reaction at model creation?Dog object cant exist before Animal object. Thanks, you’re great.

    • Derek Banas says:

      The double underscore isn’t really private, but it just makes it inconvenient to access those variables. Many people prefer to just use a single underscore to tell others not to mess with it, but at the same time it will be available by subclasses. Yes Dog can’t exist unless Animal exists. I hope that helps. Sorry that took so long 🙂

  14. Marko says:

    Derek, can you explain me this? When Dog object call Animal constructor -super(Dog, self)-, he actually pass two arguments or not? What Dog as argument means? Can you explain me this, please. Python is little strange language.

    • Derek Banas says:

      Python is a little starnge because you have to pass the Dog in this situation to have the super class Animal set up the attributes. You don’t do it that way in other languages. Does that make sense?

      • Marko says:

        Thank you Derek on answer. I am confused with (Dog, self) statement. Self is same as this in Java, and what Dog represent? I don’t see any purpose of Dog. A type of object? I’m sorry to bother you.

        • Derek Banas says:

          The subclass Dog is initialized by the Super class. That is why it is passed in. This happens with Java, but everything is hidden and you don’t have to pass the subclass like you do with python.

  15. i dont whats going on in this tutorial….actually i am confused about these things like what is sel._attribute etc….i know abt dictionary but dont know what are you doing here….can u suggest me a book or ebook to clear them
    ???please help me

Leave a Reply

Your email address will not be published.