Skip to content

OOPs in Python

surendrabisht edited this page Aug 23, 2020 · 2 revisions

Object oriented Approach

We can also use object oriented approach in python to solve any problem. So we can have classes in python.

In Python, we can add any property to object even though not defined in class.


class Python:
      pass

Now using object of class

language=Python()
language.AddAnyNewProperty="Addded Static Type checking in Python"

print(language.AddAnyNewProperty)

Basic Concepts

  1. self -> denotes current object.
  2. __init__ -> to provide your own constructor
  3. __ is dunder which can be used to denote the function as special methods and can also be use for fields to make them use as private. Even though we cannot actually make the class variables private. Dunder used in variables make them visible outside little different from other variables. we have to specify it as object._classname__privateVariable
  4. Class methods in python can be used as alternative constructor. class attributes will be changes for all instance if we change it from any instance.
  5. Static methods are used as utility methods and can't access instance and class variables.They are written in class as they are related to class but they don't modify state of the class.
  6. Python has one disadvantage of Being dynamically Typed . Hence, can introduce lot of bugs when a variable expecting to be string gets a value of some other type or etc. etc. . to avoid such cases, Python has introduced some conventions to specify what type is expected.
    in below example, code highlighted in bold is extra code to specify static type checking.

class Room:
     __totalChairs=4
     def __init__(self,roomNo:str) ->str :
         self.roomNo=roomNo
         self.__totalChairs=2

Clone this wiki locally