Posts

Showing posts from January, 2019

OOP concept in Python - Part 2

Image
Methods  One way we can improve our use of classes is to add functions to them. These class functions are known by their more common name, methods. In Python, methods are defined as part of the class definition, but can be invoked only on an instance. In other words, the path one must take to finally be able to call a method goes like this: (1) define the class (and the methods), (2) create an instance, and finally, (3) invoke the method on that instance.  Here is an example class with a method class MyDataWithMethod(object):             # define the class  def printFoo(self):                                    # define the method  print 'You invoked printFoo()!' You will notice the self argument, which must be present in all method declarations. That argument, representing the instance object, is passed to the method implicitly by the interpreter when you invoke a method on an instance, so you, yourself, do not have to worry about passing anything in (specifi

OOP concept in Python - Part 1

Image
Classes and Instances Classes and instances are related to each other: classes provide the definition of an object, and instances are "the real McCoy," the objects specified in the class definition brought to life. Here is an example of how to create a class:  class MyNewObjectType(bases):  'define MyNewObjectType class'   class_suite The keyword is class, followed by the class name. What follows is the suite of code that defines the class. This usually consists of various definitions and declarations. The biggest difference between declaring new-style classes and classic classes is that all new-style classes must inherit from at least one parent class. The bases argument is one (single inheritance) or more (multiple inheritance) parent classes to derive from. The "mother of all classes" is object. If you do not have any ancestor classes to inherit from, use object as your default. It must exist at the top of every class hierarchy. If you do n