• Latest
  • Trending
How to Use Object Oriented Programming in Python

How to Use Object Oriented Programming in Python

February 28, 2022
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022
Fibre optic interconnection linking Cameroon and Congo now operational

Fibre optic interconnection linking Cameroon and Congo now operational

July 15, 2022
Ericsson and MTN Rwandacell Discuss their Long-Term Partnership

Ericsson and MTN Rwandacell Discuss their Long-Term Partnership

July 15, 2022
Airtel Africa Purchases $42M Worth of Additional Spectrum

Airtel Africa Purchases $42M Worth of Additional Spectrum

July 15, 2022
Huawei steps up drive for Kenyan talent

Huawei steps up drive for Kenyan talent

July 15, 2022
TSMC predicts Q3 revenue boost thanks to increased iPhone 13 demand

TSMC predicts Q3 revenue boost thanks to increased iPhone 13 demand

July 15, 2022
Facebook to allow up to five profiles tied to one account

Facebook to allow up to five profiles tied to one account

July 15, 2022
Top 10 apps built and managed in Ghana

Top 10 apps built and managed in Ghana

July 15, 2022
MTN Group to Host the 2nd Edition of the MoMo API Hackathon

MTN Group to Host the 2nd Edition of the MoMo API Hackathon

July 15, 2022
KIOXIA Introduce JEDEC XFM Removable Storage with PCIe/NVMe Spec

KIOXIA Introduce JEDEC XFM Removable Storage with PCIe/NVMe Spec

July 15, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Monday, 6 February, 2023
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

How to Use Object Oriented Programming in Python

Python has excellent support for object-oriented programming. Learn what that means, why it's useful, and how you can work with objects in Python.

by ITECHNEWS
February 28, 2022
in Data Science, Leading Stories
0 0
0
How to Use Object Oriented Programming in Python

Object-Oriented Programming (OOP) is a form of programming centered around objects: small units that combine data and code. Simula was the first OOP language created for the simulation of physical models. Using OOP, you can define classes that act as templates for objects of specific types.

The core elements of OOP are classes, objects, methods, and attributes. OOP uses these elements to achieve fundamental aims: encapsulation, abstraction, inheritance, and polymorphism.

YOU MAY ALSO LIKE

Inaugural AfCFTA Conference on Women and Youth in Trade

Instagram fined €405m over children’s data privacy

Python has excellent support for object-oriented programming. If you’re wondering about OOP or how to use it in Python, read on for the details.

What Is Object-Oriented Programming in Python?

Python is a general-purpose programming language that supports object-oriented programming. Its central infrastructure aims at object and class-building applications or designing. Using OOP makes Python code cleaner and clearer. It also provides for easier maintenance and code reuse.

Here is an example to show you why to use OOP in Python.

jeans = [30, true, "Denim", 59]

In this example, jeans contain a list of values representing price, whether the item is on sale, its material, and cost. This is a non-OOP approach and causes some problems. For example, there is no explanation that jeans[0] refers to size. This is highly unintuitive compared to an OOP approach which would refer to a named field: jeans.size.

This example code isn’t very reusable since the behavior it relies on isn’t discoverable. Using OOP, you can create a class to avoid this problem.

How to Define a Class in Python

To create a class in Python, use the keyword “class” followed by your chosen name. Here’s an example defining a class named Myclass.

class MyClass:
   x = 2
 
p1 = MyClass()
print(p1.x)

Let’s define a class, Pant, to represent various types of pants. This class will contain the size, on-sale status, material, and price. By default, it initializes those values to None.

class Pant:
    # Define the properties and assign None value 
    size = None
    onsale = None
    material = None
    price = None

How to Create an Object in Python

Now let’s initialize an object from the Pant class. First, we’ll define the initializer method which has the predefined name _init_. Once you define it, Python will automatically call this method whenever you create an object from that class.

Secondly, a particular self parameter will allow the initialize method to select a new object.

Finally, after defining the initializer, we’ll create an object named jeans, using the [objectName] = Pant() syntax.

class Pant:
    # Define the initializer method 
    def __init__(self, size, onsale, material, price):
        self.size = size
        self.onsale = onsale
        self.material = material
        self.price = price
 
# Create an object of the Pant class and set each property to an appropriate value 
jeans = Pant(11, False, "Denim", 81)

Use Attributes and Methods to Define Properties and Behaviors

Objects in Python can use two different types of attribute: class attributes and instance attributes.

Class attributes are variables or methods that all objects of that class share. In contrast, instance attributes are variables that are unique to each object—the instance of a class.

Let’s create an instance method to interact with object properties.

class Pant:
    # Define the initializer method 
    def __init__(self, size, onsale, material, price):
        self.size = size
        self.onsale = onsale
        self.material = material
        self.price = price
 
    # Instance method 
    def printinfo (self):
        return f"This pair of pants is size {self.size}, made of {self.material}, and costs {self.price}"
 
    # Instance method 
    def putonsale (self):
        self.onsale = True
 
jeans = Pant(11, False, "Denim", 81)
print(jeans.printinfo())
jeans.putonsale()
print(jeans.onsale)

Here, the first method, printinfo(), uses all properties except onsale. The second method, putonsale(), sets the value of the onsale property. Note how both these instance methods use the keyword self. This refers to the particular object (or instance) used to invoke the method.

When we call putonsale(), this method uses the self parameter to change the value of that specific object. If you’d created another instance of Pant—leggings, for example—this call would not affect it. An instance property of one object is independent of any others.

How to Use Inheritance in Python

You can expand the above example by adding a subcategory of the Pant class. In object-oriented programming, this is known as inheritance. Expanding the class will define extra properties or methods that are not in the parent class.

Let’s define Leggings as a subclass and inherit it from Pant.

# Leggings is the child class to parent class Pant 
class Leggings(Pant):
   def __init__(self, size, onsale, material, price, elasticity):
       # Inherit self, size, onsale, material, and price properties 
       Pant.__init__(self, size, onsale, material, price)
       
       # Expand leggings to contain extra property, elasticity 
       self.elasticity = elasticity
 
   # Override printinfo to reference "pair of leggings" rather than "pants" 
   def printinfo(self):
       return f"This pair of leggings is size {self.size}, made of {self.material}, and costs {self.price}"
 
leggings = Leggings(11, False, "Leather", 42, True)
print(leggings.printinfo())

The new initializer method takes all the same properties as the Pant class and adds a unique elasticity property. You can extend a class to reuse existing functionality and reduce code length. If your Leggings class did not inherit from the Pant class, you would need to reproduce existing code, just for a small change. You’ll notice these benefits more when you work with larger and more complicated classes.

Check if an Object Inherits From a Class With isinstance()

The isinstance() function checks if an object is an instance of a specific class or any of its ancestor classes. If the object is of the given type, or a type that inherits from it, then the function returns True. Otherwise, it’ll return False.

# Dummy base class 
class Pant:
   None
 
# Dummy subclass that inherits from Pant 
class Leggings(Pant):
   None
 
pants = Pant()
leggings = Leggings()
 
print(isinstance(leggings, Pant))
print(isinstance(pants, Leggings))

Note that Python considers the leggings object, of type Leggings, an instance of Pant, the parent class of Leggings. But a pants object is not an instance of the Leggings class.

Python Is the Perfect Introduction to OOP

Python has gained popularity because of its simple and easy-to-understand syntax compared with other programming languages. The language was designed around object-oriented programming, so it’s a great tool to learn the paradigm. Most large tech companies make use of Python at some point in their technology stack, and the prospects look good for Python programmers.

Source: ZADHID POWELL
Via: makeuseof
Tags: Oriented Programming in Python
ShareTweetShare
Plugin Install : Subscribe Push Notification need OneSignal plugin to be installed.

Search

No Result
View All Result

Recent News

Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022

Recent News

  • Inaugural AfCFTA Conference on Women and Youth in Trade September 6, 2022
  • Instagram fined €405m over children’s data privacy September 6, 2022
  • 5.7bn data entries found exposed on Chinese VPN August 18, 2022
  • Fibre optic interconnection linking Cameroon and Congo now operational July 15, 2022
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Go to mobile version