xxxxxxxxxx
<__main__.Robot object at 0x7fd0080b3ba8> <class '__main__.Robot'>
<__main__.PhysicianRobot object at 0x7fd0080b3b70> <class '__main__.PhysicianRobot'>
Hi, I am James
xxxxxxxxxx
# Python code to demonstrate how parent constructors
# are called.
# parent class
class Person( object ):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
# child class
class Employee( Person ):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)
# creation of an object variable or an instance
a = Employee('Rahul', 886012, 200000, "Intern")
# calling a function of the class Person using its instance
a.display()
xxxxxxxxxx
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
xxxxxxxxxx
class Person:
residence = "Planet Earth" # Class attribute
def __init__(self, name, age): # Constructor
self.name = name # "self" refers to the current instance of a class
self.age = age # instance attribute
self.height = 0
def introduce(self): # instance method
print(f"Hello, my name is {self.name}")
@classmethod
def wake_up(): # class method, defined with @classmethod decorator
print("Time to start your day!")
john = Person("John Casey", 38) # This invokes a call to __init__
john.age # Retrieve the age instance attribute
print(Person.residence) # class attributes are accessed without an instance
john.introduce() # instance method Called on a Person object
Person.wake_up() # Calling a class method
class Employee(Person): # Inheritance : Employee is the child class, Person is the parent class
def __init__(self, name, age, title):
super().__init__(name, age) # this is same as : "Person.__init__(self, name, age)"
self.title = title
def introduce(self): # Overriding, changing method in child class which was previously available in parent class
print(f"""My name is {self.name}, I am a {self.title}""")
def __eq__(self, other): # Overloading : Customize the behavior of Python operators for a class, applicable to magic methods
return self.name == other.name
lester = Employee("Lester", 26, "Technician")
lester.introduce() # overriden method called
# Comparison
chuck = Person("Charles Carmichael")
charles = Person("Charles Carmichael")
print(chuck == charles) # Overloading method called
# Multiple inheritance : When a child class has more than one parent
# Multilevel inheritance : In a multiple inheritance, when one of the parent is a derived class itself
# Method resolution order (MRO) : If multiple parent class has method with same name, access right is children first, then left-to-right as defined in extending the parent class names
class Student:
def __init__(self, school):
self.school = school
self.courses = []
def add_course(self, course_name):
self.courses.append(course_name)
class Intern(Employee, Student): # Multiple inheritance
def __init__(self, department, school, duration):
# Make a call to BOTH constructors
Employee.__init__(self, department)
Student.__init__(self, school)
self.duration = duration
stephen = Intern("Software Development", "Echo University", 10)
stephen.introduce() # Method from Employee
stephen.add_course("Intermediate OOP in Python") # Method from Student
print(Intern.mro()) # See MRO precedences for same name methods
xxxxxxxxxx
# this is the class which will become
# the super class of "Subclass" class
class Class():
def __init__(self, x):
print(x)
# this is the subclass of class "Class"
class SubClass(Class):
def __init__(self, x):
# this is how we call super
# class's constructor
super().__init__(x)
# driver code
x = [1, 2, 3, 4, 5]
a = SubClass(x)
xxxxxxxxxx
class Base():
""" My base class """
__nb_instances = 0
def __init__(self):
Base.__nb_instances += 1
self.id = Base.__nb_instances
class User(Base):
""" My User class """
def __init__(self):
super().__init__()
self.id += 99
u = User()
print(u.id)
xxxxxxxxxx
class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
def say_hi(self):
print("Everything will be okay! ")
print(self.name + " takes care of you!")
y = PhysicianRobot("James")
y.say_hi()
xxxxxxxxxx
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Michael", "Smith", 2020)
xxxxxxxxxx
# 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):
self.name = name
# To get name
def getName(self):
return self.name
# To check if this person is an employee
def isEmployee(self):
return False
# Inherited or Subclass (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(emp.getName(), emp.isEmployee())
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())
xxxxxxxxxx
# 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):
self.name = name
# To get name
def getName(self):
return self.name
# To check if this person is an employee
def isEmployee(self):
return False
# Inherited or Subclass (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(emp.getName(), emp.isEmployee())
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())
xxxxxxxxxx
class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I am " + self.name)
class PhysicianRobot(Robot):
pass
x = Robot("Marvin")
y = PhysicianRobot("James")
print(x, type(x))
print(y, type(y))
y.say_hi()