Python Class
A class is a code blueprint for creating objects. In python, a class is created by the class keyword. Using the constructor of a class we create its object. In Python, we create class in the following manner.
Declaring a Class
class name: statements
Example:
class Point: x = 0 y = 0 # main p1 = Point() p1.x = 2 p1.y = -5
from Point import * # main p1 = Point() p1.x = 7 p1.y = -3 # Python objects are dynamic (can add fields any time!) p1.name = "Tyler Durden"
Objects Methods
def name (self, parameter, ....., parameter): statements
In the above code, self keyword is very important, as, without the presence of self, python will not allow to use any of the class member functions. It is similar to “this” keyword used in Java. With only a difference that in java using “this” is not mandatory.
from math import * class Point: x = 0 y = 0 def set_location(self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy)
In the above code, we have created 3 methods that is set_location(), distance_from_origin() and distance().
Python Class Constructors
A constructor is a special method with the name __init__.
def __init__ (self, parameter, ....., parameter): statements
Example:
class Point: def __init__( self, x, y): self.x = y self.y = y
toString and __str__
It is similar to Java’s toString() method which converts objects to a string. It is automatically involved when str or print is called.
def __str__( self): return string
Example:
from math import * class Point: def __init__(self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy) def translate(self, dx, dy): self.x += dx self.y += dy def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"