< Example 1 > Defining Class
class myInteger:
value = 0 # define a global variable within the class.
# you can use this variable in anyware within the class by
# 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() # create an instance of the class
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 04 > Inherit another class
class Animal:
species = ""
def __init__(self,species):
self.species = species
def getSpecies(self):
return self.species
class Dog(Animal): # Define a class Dog which inherits the class Animal
def __init__(self):
super().__init__("Dog")
dog = Dog();
print(dog.getSpecies())
Result :------------------------------
Dog
< Example xx >
|