Python Class and Object - Letsprogram

Share:
Python is an Objective Oriented Programming i.e; it follows objective oriented principles. Class is one of the principles of objective programming. Almost everything in python is an Object.

A Class bundles both data and functions together. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

Python Class follows inheritance and multiple base classes. A derived class can override base class methods. And a method can call the base class method with the same name.

Class is a blueprint for an object. Class never occupies memory in the system, the memory is occupied by the object. An object follows the rules defined in the class.
We can do aliasing in python which is multiple names (in multiple scopes) that can be bound to a single object.

Class and object relation



SYNTAX for Class :

class ClassName:
    <statement 1>
    .
    .
    <statement n>

In general, statements may be functions or variables. When you create a class definition a new namespace is created where all assignments of local variables go into this new namespace. We discuss namespaces in another post.

class object supports two kinds of operations 
  1. Instantiation
  2. attribute references
class example:
      """ A simple Example class """
      i=2020
      def f(self):
           return "Hello"
      def __init__(self,a,b):
           self.a = a
           self.b = b

consider the above class, then example.i, example.f are valid attribute references
Class attributes can also be assigned so that you can change the value of I from the class example.

class instantiation uses the function notation if any parameters are required you can give it.

x = example(20,30)

You are giving the class object to the local variable x. Here, it takes parameters because of the constructor.

when a class defines an __init__() method, class instantiation invokes this method automatically for newly created class instances. __init__( ) method may take arguments for better operations in that case class instantiation takes the arguments and give to the __init__( ) method.

We discussed earlier that almost everything in python is an object to know the type of the object use type(object)  or object.__class__

-----> methods from the same class call the other methods in the class by using self argument :

class book:
    def __init__(self):
        self.data=[]
    def add(x):
        self.data.append(x)
    def addtwice(x)
        self.add(x)
        self.add(x)

When addtwice() function accessed through an object then it will call add function from the same class.   


No comments

F