Classes
Classes are the key features of object-oriented programming. A class is a structure for
representing an object and the operations that can be performed on the object.
In Python a class can contain attributes (variables) and methods (functions).
A class is defined almost like a function, but using the class keyword, and the class definition
usually contains a number of class method definitions (a function in a class).
• Each class method should have an argument self as it first argument. This
object is a self-reference.
• Some class method names have special meaning, for example:
– __init__: The name of the method that is invoked when the object is first
created.
– __str__ : A method that is invoked when a simple string representation of the
class is needed, as for example when printed.
– There are many more, see
[Link]
– [Link]
from [Link] import Image
Image(filename='../../Images/[Link]')
Image(filename='../../Images/[Link]')
class Point:
def __init__(self, x, y):
"""
Create a new Point at x, y.
"""
self.x = x
self.y = y
def translate(self, dx, dy):
"""
Translate the point by dx and dy in the x and y direction.
"""
self.x += dx
self.y += dy
def __str__(self):
return("Point at [%f, %f]" % (self.x, self.y))
To create a new instance of a class:
p1 = Point(0, 0) # this will invoke the __init__ method in the Point
class
print("1: ", p1) # this will invoke the __str__ method
1: Point at [0.000000, 0.000000]
To invoke a class method in the class instance p:
p2 = Point(1, 1)
[Link](0.25, 1.5)
print("1: ", p1)
print("2: ", p2)
1: Point at [0.250000, 1.500000]
2: Point at [1.000000, 1.000000]
Another example
class Circle:
pi = 3.14
# Circle gets instantiated with a radius (default is 1)
def __init__(self, radius=1):
[Link] = radius
[Link] = radius * radius * [Link]
# Method for resetting Radius
def setRadius(self, new_radius):
[Link] = new_radius
[Link] = new_radius * new_radius * [Link]
# Method for getting Circumference
def getCircumference(self):
return [Link] * [Link] * 2
c = Circle()
print('1: Radius is: ',[Link])
print('2: Area is: ',[Link])
print('3: Circumference is: ',[Link]())
1: Radius is: 1
2: Area is: 3.14
3: Circumference is: 6.28