Tuesday, June 15, 2021

Python 3 - refresh concepts 1

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment


The following line of the program displays the prompt and, the statement saying “Press the enter key to exit”, and then waits for the user to take action −

input("\n\nPress the enter key to exit.")



The semicolon ( ; ) allows multiple statements on a single line given that no statement starts a new code block. Here is a sample snip using the semicolon −

import sys; x = 'foo'; sys.stdout.write(x + '\n')



class ClassName:

   'Optional class documentation string'

   class_suite


  • The class has a documentation string, which can be accessed via ClassName.__doc__
  • The class_suite consists of all the component statements defining class members, data attributes and functions.

class Employee:

   'Common base class for all employees'

   empCount = 0


   def __init__(self, name, salary):

      self.name = name

      self.salary = salary

      Employee.empCount += 1

   

   def displayCount(self):

     print ("Total Employee %d" % Employee.empCount)


   def displayEmployee(self):

      print ("Name : ", self.name,  ", Salary: ", self.salary)



Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −

  • __dict__ − Dictionary containing the class's namespace.
  • __doc__ − Class documentation string or none, if undefined.
  • __name__ − Class name.
  • __module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode.
  • __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.


Destroying Objects (Garbage Collection)

Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed as Garbage Collection.

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it is deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

a = 40      # Create object <40>

b = a       # Increase ref. count  of <40> 

c = [b]     # Increase ref. count  of <40> 


del a       # Decrease ref. count  of <40>

b = 100     # Decrease ref. count  of <40> 

c[0] = -1   # Decrease ref. count  of <40> 


This __del__() destructor prints the class name of an instance that is about to be destroyed −


class Point:

   def __init__( self, x=0, y=0):

      self.x = x

      self.y = y

   def __del__(self):

      class_name = self.__class__.__name__

      print (class_name, "destroyed")


pt1 = Point()

pt2 = pt1

pt3 = pt1

print (id(pt1), id(pt2), id(pt3))   # prints the ids of the obejcts

del pt1

del pt2

del pt3



Class Inheritance

Instead of starting from a scratch, you can create a class by deriving it from a pre-existing class by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.



Base Overloading Methods

The following table lists some generic functionality that you can override in your own classes 


__init__ ( self [,args...] )

Constructor (with any optional arguments)

Sample Call : obj = className(args)



__del__( self )

Destructor, deletes an object

Sample Call : del obj


__repr__( self )

Evaluatable string representation

Sample Call : repr(obj)



__str__( self )

Printable string representation

Sample Call : str(obj)


__cmp__ ( self, x )

Object comparison

Sample Call : cmp(obj, x)



Overloading Operators

Suppose you have created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.

You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation −



#!/usr/bin/python3


class Vector:

   def __init__(self, a, b):

      self.a = a

      self.b = b


   def __str__(self):

      return 'Vector (%d, %d)' % (self.a, self.b)

   

   def __add__(self,other):

      return Vector(self.a + other.a, self.b + other.b)


v1 = Vector(2,10)

v2 = Vector(5,-2)

print (v1 + v2)


Suppose you have created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.

You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation −





References:

https://www.tutorialspoint.com/python3/python_basic_syntax.htm

No comments:

Post a Comment