Tutorial

Python Classes and Objects

Published on August 4, 2022
author

Pankaj

Python Classes and Objects

Python is an object-oriented programming language. Python Classes and Objects are the core building blocks of Python programming language.

Python Class

By this time, all of you should have already learned about Python Data Types. If you remember, basic data types in python refer to only one kind of data at a time. How would it be if you could declare a data type which itself contains more than one data types and can work with them with the help of any function? Python class gives you that opportunity. Python class is the blueprint on which instances of the class are created.

Simple Python Class Declaration

Here’s the very basic structure of python class definition.

class ClassName:  
    # list of python class variables  
    # python class constructor  
    # python class method definitions

Now, let’s work with real examples.

#definition of the class starts here  
class Person:  
    #initializing the variables  
    name = ""  
    age = 0  
      
    #defining constructor  
    def __init__(self, personName, personAge):  
        self.name = personName  
        self.age = personAge  
  
    #defining class methods  
    def showName(self):  
        print(self.name)  
  
    def showAge(self):  
        print(self.age)  
          
    #end of the class definition  
  
# Create an object of the class  
person1 = Person("John", 23)  
#Create another object of the same class  
person2 = Person("Anne", 102)  
#call member methods of the objects  
person1.showAge()  
person2.showName() 

This example is pretty much self-explanatory. As we know, the lines starting with “#” are python comments. The comments explain the next executable steps. This code produces the following output. Output of python class example

Python Class Definition

class Person: 

This line marks the beginning of class definition for class ‘Person’.

Python Class Variables

    #initializing the variables  
    name = ""  
    age = 0

‘name’ and ‘age’ are two member variables of the class ‘Person’. Every time we declare an object of this class, it will contain these two variables as its member. This part is optional as they can be initialized by the constructor.

Python Class Constructor

    #defining constructor  
    def __init__(self, personName, personAge):  
        self.name = personName  
        self.age = personAge

Python class constructor is the first piece of code to be executed when you create a new object of a class. Primarily, the constructor can be used to put values in the member variables. You may also print messages in the constructor to be confirmed whether the object has been created. We shall learn a greater role of constructor once we get to know about python inheritance. The constructor method starts with def __init__. Afterward, the first parameter must be ‘self’, as it passes a reference to the instance of the class itself. You can also add additional parameters like the way it is shown in the example. ‘personName’ and ‘personAge’ are two parameters to sent when a new object is to be created.

Python Class Methods

#defining python class methods  
    def showName(self):  
        print(self.name)  

Methods are declared in the following way:

def method_name(self, parameter 1, parameter 2, …….)
    statements……..
    return value (if required)

In the pre-stated example, we’ve seen that the method showName() prints value of ‘name’ of that object. We shall discuss a lot more about python methods some other day.

Python Class Object

# Create an object of the class  
person1 = Person("Richard", 23)  
#Create another object of the same class  
person2 = Person("Anne", 30)  

#call member methods of the objects  
person1.showAge()
person2.showName()

The way objects are created in python is quite simple. At first, you put the name of the new object which is followed by the assignment operator and the name of the class with parameters (as defined in the constructor). Remember, the number and type of parameters should be compatible with the parameters received in the constructor function. When the object has been created, member methods can be called and member attributes can be accessed (provided they are accessible).

#print the name of person1 by directly accessing the ‘name’ attribute
print(person1.name)

That’s all for the basics of python class. As we are going to learn about python object-oriented features like inheritance, polymorphism in the subsequent tutorials, we shall learn more about python class and its features. Till then, happy coding and good bye! Feel free to comment if you have any query. Reference: Python.org Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 20, 2020

Python class constructor to initialise 2D array

- kavitha

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 25, 2020

    # Create an object of the class person1 = Person(“John”, 23) #Create another object of the same class person2 = Person(“Anne”, 102) #call member methods of the objects person1.showAge() person2.showName() should output:: 23\nAnne

    - Arny

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 11, 2019

      john’s name is not found in the program but the output is there. output mismatch with our program

      - muhi

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Become a contributor for community

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        DigitalOcean Documentation

        Full documentation for every DigitalOcean product.

        Resources for startups and SMBs

        The Wave has everything you need to know about building a business, from raising funding to marketing your product.

        Get our newsletter

        Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

        New accounts only. By submitting your email you agree to our Privacy Policy

        The developer cloud

        Scale up as you grow — whether you're running one virtual machine or ten thousand.

        Get started for free

        Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

        *This promotional offer applies to new accounts only.