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

Python Classes and Objects

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Python Object Oriented Programming

Python Inheritance
Python is a versatile programming
language that supports various
Inheritance is a way of creating a new
programming styles, including object-
oriented programming (OOP) through the class for using details of an existing class
use of objects and classes. without modifying it.

An object is any entity that has attributes The newly formed class is a derived class
and behaviors. For example, a parrot is an (or child class). Similarly, the existing
object. It has
class is a base class (or parent class).
• attributes - name, age, color, etc.
• behavior - dancing, singing, etc.
Example 2: Use of Inheritance in
Python
Python Class and Object
# base class
class Parrot: class Animal:

# class attribute def eat(self):


name = "" print( "I can eat!")
age = 0
def sleep(self):
# create parrot1 object print("I can sleep!")
parrot1 = Parrot()
parrot1.name = "Blu" # derived class
parrot1.age = 10 class Dog(Animal):

# create another object parrot2 def bark(self):


parrot2 = Parrot() print("I can bark! Woof woof!!")
parrot2.name = "Woo"
parrot2.age = 15 # Create object of the Dog class
dog1 = Dog()
# access attributes
print(f"{parrot1.name} is {parrot1.age} years # Calling members of the base class
old") dog1.eat()
print(f"{parrot2.name} is {parrot2.age} years dog1.sleep()
old")
# Calling member of the derived class
dog1.bark();
Output

Blu is 10 years old Output


Woo is 15 years old
I can eat!
I can sleep!
In the above example, we created a class
I can bark! Woof woof!!
with the name Parrot with two
attributes: name and age . Here, dog1 (the object of derived class Dog )

Then, we create instances of can access members of the base class

the Parrot class. Animal. It's because Dog is inherited

Here, parrot1 and parrot2 are references from Animal .

(value) to our new objects. # Calling members of the Animal class


dog1.eat()
dog1.sleep()
We then accessed and assigned different
values to the instance attributes using the
objects name and the . notation.
Python Encapsulation Polymorphism
Polymorphism is another important concept
Encapsulation is one of the key features
of object-oriented programming. of object-oriented programming. It simply
Encapsulation refers to the bundling of
means more than one form.
attributes and methods inside a single
class.
That is, the same entity (method or operator
It prevents outer classes from accessing or object) can perform different operations in
and changing attributes and methods of a
different scenarios.
class. This also helps to achieve data
hiding.
Let's see an example,
In Python, we denote private attributes
using underscore as the prefix i.e class Polygon:
# method to render a shape
single _ or double __ . For example, def render(self):
class Computer: print("Rendering Polygon...")

def __init__(self): class Square(Polygon):


self.__maxprice = 900 # renders Square
def render(self):
def sell(self): print("Rendering Square...")
print("Selling Price:
{}".format(self.__maxprice)) class Circle(Polygon):
# renders circle
def setMaxPrice(self, price): def render(self):
self.__maxprice = price print("Rendering Circle...")

c = Computer() # create an object of Square


c.sell() s1 = Square()
s1.render()
# change the price
c.__maxprice = 1000 # create an object of Circle
c.sell() c1 = Circle()
c1.render()
# using setter function
c.setMaxPrice(1000)
Output
c.sell()

Output
Rendering Square...
Selling Price: 900 Rendering Circle...
Selling Price: 900
Selling Price: 1000
In the above example, we have created a
In the above program, we defined superclass: Polygon and two
a Computer class.
subclasses: Square and Circle . Notice the
We used __init__() method to store the
use of the render() method.
maximum selling price of Computer . Here,
notice the code The main purpose of the render() method is
to render the shape. However, the process
c.__maxprice = 1000
of rendering a square is different from the
Here, we have tried to modify the value
process of rendering a circle.
of __maxprice outside of the class. However,
since __maxprice is a private variable, this Hence, the render() method behaves
modification is not seen on the output. differently in different classes. Or, we can
As shown, to change the value, we have to
say render() is polymorphic.
use a setter function i.e setMaxPrice() which
takes price as a parameter.
Python Classes and Objects

Python is an object oriented programming


language.

Almost everything in Python is an object,


The __str__() Function
with its properties and methods.
The __str__() function controls what
A Class is like an object constructor, or a should be returned when the class object
is represented as a string.
"blueprint" for creating objects.
If the __str__() function is not set, the
string representation of the object is
Create a Class
returned:
To create a class, use the keyword class:
Example
Example
The string representation of an object
Create a class named MyClass, with a
WITHOUT the __str__() function:
property named x:

Create Object

Now we can use the class named MyClass


Example
to create objects:
The string representation of an object
Example WITH the __str__() function:

Create an object named p1, and print the


value of x:

The __init__() Function Object Methods

All classes have a function called Objects can also contain methods.
__init__(), which is always executed when Methods in objects are functions that
the class is being initiated. belong to the object.

Use the __init__() function to assign Let us create a method in the Person
values to object properties, or other class:
operations that are necessary to do when
the object is being created: Example

Example Insert a function that prints a greeting,


and execute it on the p1 object:
Create a class named Person, use the
__init__() function to assign values for
name and age:
The self Parameter The pass Statement

The self parameter is a reference to the class definitions cannot be empty, but if
current instance of the class, and is used you for some reason have
to access variables that belongs to the a class definition with no content, put in
class. the pass statement to avoid getting an
error.
It does not have to be named self , you can
call it whatever you like, but it has to be Example
the first parameter of any function in the
class:

Example

Use the
words mysillyobject and abc instead
of self:

Modify Object Properties

You can modify properties on objects like


this:

Example

Set the age of p1 to 40:

Delete Object Properties

You can delete properties on objects by


using the del keyword:

Example

Delete the age property from the p1 object:

Delete Objects

You can delete objects by using


the del keyword:

Example

Delete the p1 object:

You might also like