# A simple example class
class Test:
# A sample method
def fun(self):
print("Hello")
Test().fun()
# Driver code
a = Test()
[Link]()
Test().fun()
------------------------------
# A Sample class with init method
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name):
[Link] = name
# Sample Method
def say_hi(self):
print('Hello, my name is', [Link])
p = Person('Shwetanshu')
p.say_hi()
---------------------------------
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1
def displayCount(self):
print ("Total Employee %d" % [Link])
def displayEmployee(self):
print ("Name : ", [Link], ", Salary: ", [Link])
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
[Link]()
[Link]()
print ("Total Employee %d" % [Link])
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__)
-------------
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
[Link] = f
[Link] = s
def display(self):
print("First number = " + str([Link]))
print("Second number = " + str([Link]))
print("Addition of two numbers = " + str([Link]))
def calculate(self):
[Link] = [Link] + [Link]
# creating object of the class
# this will invoke parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
[Link]()
# display result
[Link]()
-----------------------
Overloading
------------
class A:
def stackoverflow(self, i=0):
print ('only method',i)
ob=A()
[Link](2)
[Link]()
-------------------
Overriding
------------
Example
--------
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method')
class Child(Parent): # define child class
def myMethod(self):
print ('Calling child method')
c = Child() # instance of child
[Link]() # child calls overridden method
----------------------
# A Python program to demonstrate inheritance
-------------------------
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Person(object):
# Constructor
def __init__(self, name):
[Link] = name
# To get name
def getName(self):
return [Link]
# To check if this person is employee
def isEmployee(self):
return False
# Inherited or Sub class (Note Person in bracket)
class Employee(Person):
# Here we return true
def isEmployee(self):
return True
# Driver code
emp = Person("Geek1") # An Object of Person
print([Link](), [Link]())
--------------