Scripting >> Python >> Examples >> Class >> Class and object operations

 

 

How to create a user defined class
class MyClass:
"""A simple example class"""
i = 12345

def f(self):
return 'hello world'

To create an instance (obj) of the class

x = MyClass()

When __init__() method is defined in the class, the instantiation will invoke this method.  Can use it to initialize newlly created objects to a specific state.

>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

To delete the object >>> class Complex:
...    def __init__(self,realpart,imagpart)
...       self.r = realpart
...       self.i = imagpart
...
>>> x = Complex(3.0,-4.5)  # create
>>> del x                  # delete
>>> x.r, x.i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
Delete object property with del or delattr()

>>> class Complex:
...     def __init__(self,realpart,imagpart):
...        self.i = imagpart
...        self.r = realpart
...
>>> c = Complex(1.0,-2.0)
>>> c.i
-2.0
>>> c.r
1.0
>>> delattr(c,'i')  # first parameter is object name, 2nd is string containing property name
>>> c.i             # will return error as property .i already deleted     
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Complex instance has no attribute 'i'
>>> c.r
1.0

>>> c = Complex(1.0,-2.0)
>>> del c.i
>>> c.i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Complex instance has no attribute 'i'

 

Using inheritance

 

Example, base class Polygon

 class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i])

 

Example, derived class Triangle

class Triangle(Polygon):
    def __init__(self):
        Polygon.__init__(self,3)

    def findArea(self):
        a, b, c = self.sides
        # calculate the semi-perimeter
        s = (a + b + c) / 2
        area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
        print('The area of the triangle is %0.2f' %area)

 

Some methods inherited from base class, some methods in the derived class

>>> t = Triangle()

>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4

>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0

>>> t.findArea()

 

 Method overloading during inheritance

 eg. the __init__ method in the derived class overrides the same in the base class.

In above example it was done by calling the base class init method BaseClass.__init__ .e.g. Polygon.__init__

Alternate method is to use super().__init()__