Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOPS6

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

• Self is just a conventional name for the first argument of a method in

the class. A method defined as mymethod(self, a, b) should be called


as x.mymethod(a, b) for the object x of the class.
• The above class method can be called as a normal function, as shown
below.
• >>> std = Student()
• >>> std.displayInfo()
• 'Student Information'
• The first parameter of the method need not be named self. You can
give any name that refers to the instance of the calling method. The
following displayInfo() method names the first parameter as obj
instead of self and that works perfectly fine.
• class Student:
• def displayInfo(obj): # class method
• print('Student Information')
• Defining a method in the class without the self parameter would raise an exception
when calling a method.
• Example: Class Method
• class Student:
• def displayInfo(): # method without self parameter
• print('Student Information')
• >>> std = Student()
• >>> std.displayInfo()
• Traceback (most recent call last):
• std.displayInfo()
• TypeError: displayInfo() takes 0 positional arguments but 1 was given
• The method can access instance attributes using the self parameter.
• class Student:
• def __init__(self, name, age):
• self.name = name
• self.age = age
• def displayInfo(self): # class method
• print('Student Name: ', self.name,', Age: ', self.age)
• You can now invoke the method, as shown below.
• >>> std = Student('Steve', 25)
• >>> std.displayInfo()
• Student Name: Steve , Age: 25
Deleting Attribute, Object, Class

• Deleting Attribute, Object, Class


• You can delete attributes, objects, or the class itself, using the del
keyword, as shown below.
• >>> std = Student('Steve', 25) • File "<pyshell#42>", line 1, in <module>
• >>> del std.name # deleting attribute • std.name
• >>> std.name • NameError: name 'std' is not defined
• Traceback (most recent call last): • >>> del Student # deleting class
• File "<pyshell#42>", line 1, in <module> • >>> std = Student('Steve', 25)
• std.name • Traceback (most recent call last):
• AttributeError: 'Student' object has no • File "<pyshell#42>", line 1, in <module>
attribute 'name' • std = Student()
• >>> del std # deleting object • NameError: name 'Student' is not
• >>> std.name defined
• Traceback (most recent call last):
Inheritance in Python

• Inheritance in Python
• We often come across different products that have a basic model and
an advanced model with added features over and above basic model.
A software modelling approach of OOP enables extending the
capability of an existing class to build a new class, instead of building
from scratch. In OOP terminology, this characteristic is called
inheritance, the existing class is called base or parent class, while the
new class is called child or sub class.

You might also like