We will see the OOPs implementation in Python along with examples.
Object-oriented programming can model real-life scenarios and suit the development of large and complex applications.
In real life, an object is something that you can sense and feel. For example Car, Bicycles, Mango, and more.
However, in Software development, an object is a non-tangible entity, which holds some data and is capable of doing certain things.
A Class is a template that contains:
1. instructions to build an object.
2. methods that can be used by the object to exhibit a specific behaviour.
“class” keyword is used to define a class in Python.
Syntax
class <ClassName>(<parent1>, ... ):
class_body
Example:
class Person:
pass
Above example defines Person class without anybody.
An object is created by calling the class name followed by a pair of parenthesis.
class Person:
pass
p1 = Person() # Creating the object 'p1'
>>>print(p1)
The output of print on object p1, tell you what class it belongs to and hints at the memory address it is referenced to.
You can set attributes, one at a time, to an instantiated object and access it using the dot notation.
The value which is set to an attribute can be anything: a Python primitive, a built-in data type, or another object. It can even be a function or a class.
Example
class Person:
pass
p1 = Person()
p1.fname = 'Jack'
p1.lname = 'Simmons'
>>>print(p1.fname, '-', p1.lname) # -> 'Jack - Simmons'
1. You can also set multiple attributes, at once, by defining the initializer method, __init__, inside the class.
2. This method is called by default, during an object creation.
3. It takes values passed inside the parenthesis, during an object creation, as it's arguments.
4. It also takes self as the first argument, which refers to the current object.
5. In the following example, the Person class sets two attributes using __init__ method.
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
p1 = Person('George', 'Smith')
print(p1.fname, '-', p1.lname) # -> 'George - Smith'
Each class or a method definition can have an optional first line, known as docstring.
Example:
class Person:
'Represents a person.'
def __init__(self, fname, lname):
'Initialises two attributes of a person.'
self.fname = fname
self.lname = lname
Once documented, you can load the script into an interactive interpreter and run the help command on the Person class.
>>>help(Person)
Help on class Person in module __main__:
class Person(builtins.object)
| Represents a person.
|
| Methods defined here:
|
| __init__(self, fname, lname)
| Initialises two attributes of a person.
If you have questions, or simply would like to share your thoughts, then feel free to reach out in the comments section below.