Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - Class

 

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Defining a Class  - Example 1
  • Defining a Class with Constructor   - Example 2
  • Defining a Class with Constructor Overloading  - Example 3

 

 

Examples :

 

< Example 1 > Defining Class

 

class myInteger:

    

    value = 0

    

    def increment(self, step = 1):

        self.value +=  step

        

    def decrement(self, step = 1):

        self.value -= step

        

    def getValue(self):

        return self.value

 

 

myInt = myInteger()

 

print(myInt.getValue())

 

myInt.increment()

print(myInt.getValue())

 

myInt.increment(4)

print(myInt.getValue())

 

myInt.decrement(2)

print(myInt.getValue())

 

myInt.decrement()

print(myInt.getValue())

 

 

Result :------------------------------

 

0   <--- myInt = myInteger()

1   <--- myInt.increment()

5   <--- myInt.increment(4)

3   <--- myInt.decrement(2)

2   <--- myInt.decrement()

 

 

 

< Example 02 >  Defining a Class with Constructor

 

class myInteger:

    

    value = 0

 

    def __init__(self):

        self.value = 10

        print("Initial Value = ",self.value)

    

    def increment(self, step = 1):

        self.value +=  step

        

    def decrement(self, step = 1):

        self.value -= step

        

    def getValue(self):

        return self.value

 

 

myInt = myInteger()

 

 

Result :------------------------------

 

Initial Value =  10   <--- myInt = myInteger()

 

 

 

< Example 03 >  Defining a Class with Constructor Overloading

 

class myInteger:

    

    value = 0

 

    def __init__(self, initialValue = 1):

        self.value = initialValue

        print("Initial Value = ",self.value)

    

    def increment(self, step = 1):

        self.value +=  step

        

    def decrement(self, step = 1):

        self.value -= step

        

    def getValue(self):

        return self.value

 

 

myInt1 = myInteger()

myInt2 = myInteger(10)

myInt3 = myInteger(initialValue = 5)

 

 

Result :------------------------------

 

Initial Value =  1    <--- myInt1 = myInteger()

Initial Value =  10   <--- myInt2 = myInteger(10)

Initial Value =  5    <--- myInt3 = myInteger(initialValue = 5)

 

 

 

< Example xx >