Python

Constant dripping wears away a stone

Object-oriented Programming


Classes and Objects: Python is an object oriented programming language. Class is a user defined data type that includes two parts: fields and methods. An object is an instance of a class. A class can be considered as a template that multiple objects can be created upon. Cars and different brand cars like Ford, Honda, Jeep, and Tesla, make a good example of a class and its objects.

  • Creating a Class: To create a class, use keywordclass,followed by class name:.
  • self: selfis the first parameter in a class method or the constructor of a class. It refers to the current instance of the class. It can be called any name, but it can only appear as the first parameter.
  • Constructor: _ _init(self[, parameter1, parameter2, ...])_ _ is a function inside a class. Each time when an object of a class is created, this function will be automatically called. It is called theconstructorof the class.
  • Class Variables and Instance Variables: When a variable is declared outside the class contructor, it is aclass variable. When a variable is declared inside a class constructor, it is aninstance variable. Class variables are shared by all instances of the class while instance variables are unique to their own instance. Class variables can not be mutable data types such as list, dictionary, etc., as they may produce wrong results.
  • Class Methods: Class methods are functions inside a class. A method may call another method in the same class.
  • Class Inheritance: A class can be constructed using another class as a base. Such a class is called a child class and the base class is called a parent class. Besides its own fields and methods, the child class automatically inherits all the fields and methods of its parent class. To create a child class, use the parent class as a parameter in its constructor.
  • Empty Class: Similar to an "empty function", an empty class can use thepassstatement inside the class body if the class has no fields and methods.