Uploaded by Anthony Ambrose

Python OOPs Class, Object, Inheritance and Constructor with Exa

advertisement
Python OOPs: Class, Object,
Inheritance and Constructor with
Example
By :
Steve Campbell
Updated July 11, 2023
OOPs in Python
OOPs in Python is a programming approach that focuses on
using objects and classes as same as other general
programming languages. The objects can be any real-world
entities. Python allows developers to develop applications
using the OOPs approach with the major focus on code
reusability. It is very easy to create classes and objects in
Python.
What is a Class?
A Class in Python is a logical grouping of data and functions.
It gives the freedom to create data structures that contains
arbitrary content and hence easily accessible.
For example, for any bank employee who want to fetch the
customer details online would go to customer class, where
all its attributes like transaction details, withdrawal and
deposit details, outstanding debt, etc. would be listed out.
Table of Contents:
Windsor Brokers
Up to $10,000 Deposit Bonus
OPEN
Win a New Luxury Electric Car
Trade 200+ assets with WB & get a
chance to win your dream luxury car plus
cash rewards
Open
How to define Python classes
To define class you need to consider following points
Step 1) In Python, classes are defined by the “Class” keyword
class myClass():
Step 2) Inside classes, you can define functions or methods
that are part of this class
def method1 (self):
print "Guru99"
def method2 (self,someString):
print "Software Testing:" + someString
Here we have defined method1 that prints “Guru99.”
Another method we have defined is method2 that prints
“Software Testing”+ SomeString. SomeString is the variable
supplied by the calling method
Step 3) Everything in a class is indented, just like the code in
the function, loop, if statement, etc. Anything not indented is
not in the class
NOTE: About using “self” in Python
The self-argument refers to the object itself. Hence the use of
the word self. So inside this method, self will refer to the
specific instance of this object that’s being operated on.
Self is the name preferred by convention by Pythons to
indicate the first parameter of instance methods in Python. It
is part of the Python syntax to access members of objects
Step 4) To make an object of the class
c = myClass()
Step 5) To call a method in a class
c.method1()
c.method2(" Testing is fun")
Notice that when we call the method1 or method2, we don’t
have to supply the self-keyword. That’s automatically
handled for us by the Python runtime.
Python runtime will pass “self” value when you call an
instance method on in instance, whether you provide it
deliberately or not
You just have to care about the non-self arguments
Step 6) Here is the complete code
This code is editable. Click Run to Execute
1 # Example file for working with classes
2 class myClass():
3
def method1(self):
4
print("Guru99")
5
6
def method2(self,someString):
7
print("Software Testing:" + someString)
8
9
10 def main():
11
# exercise the class methods
12
c = myClass ()
13
c.method1()
14
c.method2(" Testing is fun")
15
16 if __name__== "__main__":
17
main()
Run
How Inheritance works
Inheritance is a feature used in object-oriented
programming; it refers to defining a new class with less or no
modification to an existing class. The new class is called
derived class and from one which it inherits is called the
base. Python supports inheritance; it also supports multiple
inheritances. A class can inherit attributes and behavior
methods from another class called subclass or heir class.
Python Inheritance Syntax
class DerivedClass(BaseClass):
body_of_derived_class
Step 1) Run the following code
This code is editable. Click Run to Execute
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Example file for working with classes
class myClass():
def method1(self):
print("Guru99")
class childClass(myClass):
#def method1(self):
#myClass.method1(self);
#print ("childClass Method1")
def method2(self):
print("childClass method2")
def main():
# exercise the class methods
c2 = childClass()
c2.method1()
#c2.method2()
21 if __name__== "__main__":
22
main()
Run
Notice that the in childClass, method1 is not defined but it is
derived from the parent myClass. The output is “Guru99.”
Step 2) Uncomment Line # 8 & 10. Run the code
Now, the method 1 is defined in the childClass and output
“childClass Method1” is correctly shown.
Step 3) Uncomment Line #9. Run the code
You can call a method of the parent class using the syntax
ParentClassName.MethodName(self)
In our case, we call, myClass.method1(self) and Guru99 is
printed as expected
Step 4) Uncomment Line #19. Run the code.
Method 2 of the child class is called and “childClass
method2” is printed as expected.
Python Constructors
A constructor is a class function that instantiates an object to
predefined values.
It begins with a double underscore (_). It __init__() method
In below example we are taking name of the user using
constructor.
This code is editable. Click Run to Execute
1 class User:
2
name = ""
3
4
def __init__(self, name):
5
self.name = name
6
7
def sayHello(self):
8
print("Welcome to Guru99, " + self.name)
9
10 User1 = User("Alex")
11 User1.sayHello()
Run
Output will be:
Welcome to Guru99, Alex
Python 2 Example
Above codes are Python 3 examples, If you want to run in
Python 2 please consider following code.
This code is editable. Click Run to Execute
1 # How to define Python classes
2 # Example file for working with classes
3 class myClass():
4
def method1(self):
5
print "Guru99"
6
7
def method2(self,someString):
8
print "Software Testing:" + someString
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def main():
# exercise the class methods
c = myClass ()
c.method1()
c.method2(" Testing is fun")
if __name__== "__main__":
main()
#How Inheritance works
# Example file for working with classes
class myClass():
def method1(self):
print "Guru99"
class childClass(myClass):
#def method1(self):
#myClass.method1(self);
#print "childClass Method1"
def method2(self):
print "childClass method2"
def main():
# exercise the class methods
c2 = childClass()
c2.method1()
#c2.method2()
if __name__== "__main__":
main()
Run
Learn our next tutorial about Polymorphism in Python
Summary
“Class” is a logical grouping of functions and data. Python
class provides all the standard features of Object Oriented
Programming.
Class inheritance mechanism
A derived class that override any method of its base class
A method can call the method of a base class with the same
name
Python Classes are defined by keyword “class” itself
Inside classes, you can define functions or methods that are
part of the class
Everything in a class is indented, just like the code in the
function, loop, if statement, etc.
The self argument in Python refers to the object itself. Self is
the name preferred by convention by Pythons to indicate the
first parameter of instance methods in Python
Python runtime will pass “self” value automatically when you
call an instance method on in instance, whether you provide
it deliberately or not
In Python, a class can inherit attributes and behavior
methods from another class called subclass or heir class.
You Might Like:
Online Python Compiler (Editor / Interpreter / IDE) to Run
Code
PyUnit Tutorial: Python Unit Testing Framework (with
Example)
How to Install Python on Windows [Pycharm IDE]
Hello World: Create your First Python Program
Python Variables: How to Define/Declare String Variable
Types
Prev
Report a Bug
Next
About
About Us
Advertise with Us
Write For Us
Contact Us
Career Suggestion
SAP Career Suggestion Tool
Software Testing as a Career
Interesting
eBook
Blog
Quiz
SAP eBook
Execute online
Execute Java Online
Execute Javascript
Execute HTML
Execute Python
© Copyright - Guru99 2023
Privacy
Policy | Affiliate Disclaimer | ToS
Download