Tutorials  /  Python

Python Classes and Objects

Ccentron Redaktion · February 2024 ·4 min read ·Python, Tutorial

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

Python Class

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.

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

Now, let’s work with real examples.

Python
#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.

Python Class Definition

Code
class Person: 

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

Python Class Variables

Code
#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

Python
#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

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

Methods are declared in the following way:

Python
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

Console
# 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).

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

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Conclusion

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!

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren