Python - Class-Objects - Code
Python - Class-Objects - Code
class Test:
# A sample method
def fun(self):
print("Hello")
Test().fun()
# Driver code
a = Test()
a.fun()
Test().fun()
------------------------------
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Shwetanshu')
p.say_hi()
---------------------------------
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
-------------
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
# creating object of the class
# this will invoke parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
obj.calculate()
# display result
obj.display()
-----------------------
Overloading
------------
class A:
ob=A()
ob.stackoverflow(2)
ob.stackoverflow()
-------------------
Overriding
------------
Example
--------
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method')
----------------------
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())
--------------