Table of Contents

CLASS

Creation of a class

Class creation is the cornerstone of object-oriented programming. In this form of programming, you create a template or a model, from which you can create as many instances or objects as you like. The newly created objects differ in structure because they have different values of their variables.

A class is a container of methods and data.:

  • Methods : are functions inside class. They are either invoked on class name or instance name (Class Method, or Instance Method)

  • Variables : are either instance variables; unique to each instance, or class variables shared by all instances.

Usually, class variables are assigned to the instance variables on creation of the class object .

A class may contain fixed data as CONSTANTS or class variables.

Think of a class as a machine which produce many products, objects or instances. If you change the values in that machines, you get a different product from the same template or production line.

For example, consider the class of "CARS" which has many individual models with slight variations. Another way to think of a class as in biology :

  • class : mammals
  • species : cat
  • organism : my cat ( which is similar to all other cats, but has individual characteristics and share the same biology as all mammals, i.e. they eat, grow, mate and die)

To create class, start by :

 class ClassName():
    .........
    '''''''''

Class Variables

Class Variable is given a value inside the class during class creation. It is accessible by any instance of the class and used by any method in the class. It can also be modified by assigning it a new value outside the class or inside the methods.

    class Klass:
        i = 12345
    Klass.i = 88888
    obj.i ==> 88888

Methods

Functions inside a class are known as methods. You create a method inside the class as usual by :


def Method_Name(arguments/parameters):
    ...code....

Instance Methods are called by name of instance and class methods are called on name of Class. Class methods follow @classmethod declaration on a separate line.

Instance Method

Even if a method in class has no arguments it must have 'self' as its first argument. Instantiation of an object a means creating a class instance.

     class Klass():
        def func(self):
         return 'hello world'
     -----------------------------
     obj = Klass()
     obj.func()

     class Klass():
        def hi(self, name):
            print('Hello', name)
     ----------------------------
     a = Klass()
     a.hi('Sabry')  =prints 'Hello Sabry !
  • "def" then name of method then (args or "self") then semicolon.
  • You must leave an empty line after each class or method.
    • All methods in a class should have "self" as first argument.

Class Method

Call a class method directly without object (instance) :

    class Klass():
        @classmethod
        def method(cls):
                print "this is a class method"

        def add(self):
                print(2 + 3)
        ----------------
    Klass.method()
        a = Klass()
        a.add()

INSTANCE

An instance is a new different instance or object of the class. Values of the new object may be initialized on creation of the object.

    class MyClass():
        def multiply(self, a, b):
        return a*b
    -------------------------
    obj = MyClass(4,6)
    obj.multiply()

Calling a class documentation

Documentation makes the code writing easier to follow and reader can understand the purpose of each line of the code. At the same time, you can call this documentation, by using doc keyword.

        class MyClass():
            """A simple example class"""
        ----------------------------------------
        obj .__doc__  ==> A simple example class

The init method

This method is used to initialize instances of a class and assign arguments to them. It initializes arguments or parameters to accept assigned values on creation of the instance or give these arguments an initial value which will be modified later. The initial value can be None to make these arguments optional.

    class Complex():
        def __init__(self, r, s):
            self.r = r
            self.s = s

    x = Complex(12,23)
    x.r
    x.s

Instance Variables

These variables are unique in each instance. On the other hand, Class variables are shared by all object. Examine the following example :

    class Dog:
        kind = 'canine'         = class variable shared by all instances
        def __init__(self, name):
            self.name = name    = instance variable unique value in each instance
    -------------------------------------------------------------------------
    d = Dog('Fido')
    e = Dog('Buddy')
    d.kind   ==> canine (shared by all dogs)
    e.kind   ==> canine (shared by all dogs)
    d.name   ==> Fido (unique to d)
    e.name   ==> Buddy (unique to e)

The class Dog has a class variable "kind" (canine) which is shared by two dogs(instances/object) which have unique names (Fido and Buddy)

Superclass and Inheritance

As classes are objects that are created, they communicate with other classes and other objects by many ways. One way is to make a class a Superclass which gives access to its data and methods to other classes. Other classes can inherit these methods and data from their ancestor Super class. To inherit from a superclass, the newly created class include the name of its ancestor in the parentheses after the class name.


    class SuperKlass():
        def method(self):
            print("Hello World")

        def eql(self):
            a = [1,2,3,4]
            b = [1,2,3,4]
            print(a == b)

    class MyClass(SuperKlass):
        pass

    obj = MyClass()
    obj.eq()

MyClass inherits the method eq() from SuperKlass, even if it is empty (pass means do nothing).

Create more than one object instance from a class

A class produces many instances and each instance can use all the variables and methods inside the parent class. Inside the class, the instance variable can be used inside any method, but it has to be referred to the instance "self", i.e. "self.variable_name".

    class Animal():
        def __init__(self, animal):
            self.animal = animal

        def species(self):
            print(self.animal, " is canine")

    dog = Animal("dog") 
    fox = Animal("fox")
    wolf = Animal("wolf")
    dog.species()
    fox.species()
    wolf.species()

Classes inherit methods from other classes

    class Sclass(): =Sclass is superclass
        def m(self):
        print("Hello")

    class Klass(Sclass):
        pass
    obj = Klass() obj.m( ) =m method is a Sclass method


Klass inherits from Sclass the method m.

    class Mammal():
        def has_heart_beat(self):
            return True

    class Dog(Mammal):
        pass

    dog = Dog()
    print(dog.has_heart_beat())

Dog class inherit from Mammal class the fact (true) that dogs also have heart beats.

Ancestors of a class

To know the ancestors of a class (its superclasses), import inspect module and use function getmro() which stands for get members of class.

    import inspect 
    class Mammal(object):
        def has_heart_beat(self):
            return True

    class Dog(Mammal):
        pass

    print inspect.getmro(Dog)

How to get all instance variables in a class

To get all instance variables in a class, use dict function or vars() functions.

    class hi:
        def __init__(self):
            self.ii = "foo"
            self.kk = "bar"

    hi_obj = hi()
    print(hi_obj.__dict__.keys())
    print(vars(hi()))
    print(vars(hi()).keys())

Class as a record using empty class

A class is a container for data and methods. It creates a number of copies or instances each has its own unique values and attributes. In this way a class can be used as a record or database, if we assign values to each instance and call these values later. Here is an example.

    class Employee:
      pass
    john = Employee()
    john.name = 'John Doe' 
    john.dept = 'computer lab' 
    john.salary = 1000 
    print john.__dict__  
    #=> {'salary': 1000, 'dept': 'computer lab', 'name': 'John Doe'}

Back to Top