0
class animal(object):   
         pass

class dog(animal):
        def __init__(self):
            print "I got called"

I found this code in the book "Learn Python the hard way". I have questions about the relationship between dog and animal?

Are dog and animal both classes and does dog inherit something from animal?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
vivgandhi
  • 3
  • 3
  • 1
    Note: It's strongly suggested that you should capitalize the class names. See pep8: http://www.python.org/dev/peps/pep-0008/#naming-conventions – 0xc0de Aug 19 '13 at 05:25
  • The relation is one of inheritance. `dog` inherits all the attributes and methods of `animal`, which is to say none at all. – Asad Saeeduddin Aug 19 '13 at 05:28

3 Answers3

1

The class dog is inherited from the class animal. It means that any object of class dog gets all the attributes and methods that animal class defines. Class dog is called subclass or inherited class while the class animal is called superclass or parent class.

Usually a subclass is used to extend functionality of a class. So class dog can modify attributes and/or functionalities of animal and/or add its own.

0xc0de
  • 8,028
  • 5
  • 49
  • 75
0

In Python all classes inherit(directly or indirectly) from the object class.

as per the code you have posted, the class dog inherits from class animal. However it can have more attributes (such as fluffs) and behaviors of its own( e.g. bark) which are not common to all animals

In plain English : dog is-an animal. However dog will also have its own set of attributes as well as behaviors.

Prahalad Deshpande
  • 4,709
  • 1
  • 20
  • 22
  • 2
    Strictly speaking, the first sentence of the answer is not true (unless we're specifically talking about Python 3). http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python – NPE Aug 19 '13 at 05:20
  • 1
    Also, Python is case sensitive and `object` is spelled with a lowercase `o`. – NPE Aug 19 '13 at 05:20
  • @NPE I had editied my answer to say that alll classes directly or indirectly inherit from object. Not sure why the edit did not reflect. I will update once again – Prahalad Deshpande Aug 19 '13 at 05:33
  • @PrahaladDeshpande This is still not true. Old-style classes in Python 2 don't inherit from `object`. – glglgl Aug 19 '13 at 05:52
0

Yes they are both classes, and yes dog inherits everything from animal.

Joohwan
  • 2,374
  • 1
  • 19
  • 30