How to learn OO of python?

Harlin Seritt harlinseritt at yahoo.com
Wed May 18 08:01:11 EDT 2005


I think I know what you mean. When I first started trying to learn the
OOP aspect of Python I thought it was strange since I had started with
OOP on Java and C++. Nonetheless, once you get the hang of it, OOP will
make way more sense than all of the complications of Java and C++ class
implementations. Let me give you a quick example of what I'm talking
about:

class Animal:
   def eats(self):
      print 'The animal eats.'
   def walks(self):
      print 'The animal walks.'

"""Here the class Dog instantiates the class Animal. 'Dog' will 'do'
whatever 'Animal' does plus some other things which we will describe in
this class code."""
class Dog(Animal):
   """#the self keyword means that this function will be a class
function"""
   def communicate(self):
      print 'The dog barks.'

   """# __init__ function defines what # #will happen as soon as this
class is instantiated. Also, the overloaded variable designators (color
= None, fur = None) allow the instantiator to optionally define these
variables when called from elsewhere."""

   def __init__(self, color=None, fur=None):
      """# this time self will designate the variable 'color' # as a
class variable."""
      self.color = color
      self.fur = fur

if __name__ == '__main__':
   sparky = Dog(color="White", fur="Short")
   sparky.communicate()
   print sparky.color
   print sparky.fur
   print sparky.eats()   # Here sparky will access 'Animal' methods
that 'Dog' inherited.
   print sparky.walks()  # Another method originating from the 'Animal'
class.

What happens if you don't use 'self' inside your class code? You won't
be able to access it within the class outside of the method where you
initialized it. For instance, if you don't designate color with self
then you can only use the 'color' variable within the __init__()
method. This is useful whenever you want to use 'color' as a private
variable.

The same also goes for methods. Hopefully, you see how useful this can
be down the road. This way you won't have to use variable/method access
modifiers like Public, Private, Protected and so forth. If this doesn't
make sense or you want more clarity, please let me know.

Good luck,

Harlin Seritt




More information about the Python-list mailing list