Python Class and Objects

python class and objects

A Python class is a blueprint or template for creating objects that define a set of attributes and methods.

It is a fundamental concept in object-oriented programming (OOP) and allows programmers to organize code into reusable, modular components.

Before diving into Python Classes, let’s discuss the basic terminologies and definitions.

What are Attributes and Methods in Python Class?

While you are dealing with a Python class, an attribute is a variable that is defined inside a class.

It is similar to the normal variables, but in terms of a Python class, we call these variables attributes.

You know about the functions in Python programming language, methods are the functions that are defined inside a class.

In a nutshell, attributes are the variables and methods are the functions of a Python class.

What is a Class in Python?

In Python, a class is a blueprint for creating objects with certain attributes and behaviors.

A class is like a blueprint on the basis of which all the new objects will be created.

All the new objects will have the same properties (attributes) and methods (function).

A class is like an outline.

It defines a set of properties and methods that the objects of the class will have.

How do you define a class in Python?

To define a class, you can use the class keyword followed by the name of the class.

class Person:
    #code here

The word class is a reserved keyword in Python that is used to define a class.

Here is a very basic example of a class in Python:

class Person:
    #don't worry about this, we will discuss it later
    def __init__(self, name):
        self.name = name
    
    #a method(function) to greet user   
    def greet_user(self):
        print("Greetings,", self.name)
        
person1 = Person("Alia")
person1.greet_user()

Output

Greetings, Alia

What is an object in Python Class?

In Python, an object is an instance of a class.

A class defines a blueprint or template for creating objects, and an object is a specific instance of that class.

Let’s understand this concept with this analogy.

You want to make 100 houses with the exact same features and map.

It will be more useful if you create one single map or blueprint for all the houses.

This map or blueprint will be class.

And Each of the houses will be an object of that class.

Objects in Python have attributes and methods.

Attributes are variables that hold data associated with the object, and methods are functions that perform operations on the object.

How do you initialize an object in Python?

In the above example, person1 is an object of class person.

You can initialize an object of a class by calling that class and passing the required arguments (if any).

person1 = person("Alia")

We passed the name of the person as an argument to the class.

It will be stored as the name attribute of the object person1.

Behind the scenes the code will work something like this:

class Person:
    #don't worry about this, we will discuss it later
    #for the object person1, person1 will be passed as an argument
    #def __init__(person1, name):
        #person1.name = Alia
    def __init__(self, name):
        #this name will be assigned as name attribute of object person1 
        self.name = name
    
    #a method(function) to greet user  
    #it will look something like this
    #def greet_user(person1):
    def greet_user(self):
        #self.name means the name of the object preson1
        print("Greetings,", self.name)
        #here self.name means person1.name

#creating an object of the class Person        
person1 = Person("Alia")
#calling the greet_user() method
person1.greet_user()

Object methods in a Python Class

Any object can have the methods that were defined while defining the class.

Methods are the functions that belong to an object or class.

class Student():
    def __init__(self,name,gpa):
        self.name = name
        self.gpa = gpa
        
    def greet_student(self):
        print("Hi, My name is", self.name)
    
    def print_gpa(self):
        print("My GPA is", self.gpa)
        
student1 = Student("Marry", 4)
student1.greet_student()
student1.print_gpa()

In the example above greet_student() and print_gpa() are the methods of the class student.

Output

Hi, My name is Marry
My GPA is 4

How to modify object’s properties in python?

You can modify the properties of any object in python like this:

student1.gpa = 3.5
student1.name = "Harry"

student1.greet_student()
student1.print_gpa()

Output

Hi, My name is Harry
My GPA is 3.5

You see how the name and gpa of object student1 changed?

That how easy it is.

You can change any property of an object with just a single line of code.

How to delete object properties?

To delete the properties of any object you can simply use del keyword.

#deleting the name attribute using del keyword
del student1.name
#now we have deleted the attribute, Now let's try to print it
print(student1.name)

Output

AttributeError: ‘Student’ object has no attribute ‘name’ on line 4

This indicates that the name attribute has been deleted.

How to delete an object of a python class?

You can delete the entire object of a python class using the same del keyword.

print(student1.gpa)
del student1
print(student1.gpa)

Output

3.5
NameError: name ‘student1’ is not defined on line 20

That indicated that the object student is not found and has been deleted.

What is def __ init __(self) in Python?

__ init __() is a special method in Python that is used to declare the attributes of an object.

This default __init__() method is called every time you create an object.

The purpose of this __init__() method is to initialize the attributes of the object with the values passed.

In the above example, we used def __init__() to assign the name attribute.

class Person:
    #for the object person1, person1 will be passed as first argument and the name as second argument
    #def __init__(person1, name):
        #person1.name = Alia
    def __init__(self, name):
        #this name will be assigned as name attribute of object person1 
        self.name = name

In a nutshell, __init__() is used to assign attributes (variables) to the object.

What is Self in Python Class?

In a Python class, self is a reference to the object that is calling any method.

It is the first parameter in the definition of a method in a class, and it is conventionally name self.

When you call a method on an instance of a class, Python automatically passes the instance as the first argument to the method.

This allows the method to access the attributes and methods of the instance.

Let’s understand this with an example:

#defining a class
class Person:
    #the object that will be created as an instance of this class will be  passed as first argument as first argument of method
    def __init__(self, name, age):
        #this line defines that the name of the object should be equal to the name that will passed in the parameter while creating the object
        #let say you create an object person1 so this line will be executed as
        #person1.name = name
        self.name = name
        #similary this line will be executed as 
        #person1.age = age
        self.age = age
    
    #this is a method of class Person that will say hello
    def say_hello(self):
        print("Hello, my name is", self.name, "and my age is", self.age)

#creating an object person1
person1 = Person("Alice", 25)
#calling the say_hello() method
person1.say_hello()

Output

Hello, my name is Alice and my age is 25

The word self is used as a convention.

You can use another name that you want. For example:

class Person:
    def __init__(myObject, name, age):
        myObject.name = name
        myObject.age = age
    
    def say_hello(myObject):
        print("Hello, my name is", myObject.name, "and my age is", myObject.age)

person1 = Person("Alice", 25)
person1.say_hello()

Output

Hello, my name is Alice and my age is 25

Why is self used in Python?

self is used in Python to refer to the instance (object) of a class that calls the method.

Python will automatically pass the just-created object as the argument of the method (function).

You can use self to manipulate the attributes or variables of the object.

Moreover, you can access the attributes with this.

The word self is used as a convention.

You can use any other word you want. For example, myObject or mySillyObject.

class Person:
    def __init__(myObject, name, age):
        myObject.name = name
        myObject.age = age
    
    def say_hello(myObject):
        print("Hello, my name is", myObject.name, "and my age is", myObject.age)

person1 = Person("Alice", 25)
person1.say_hello()

Output

Hello, my name is Alice and my age is 25

What is class method __ str __?

The __str__() function controls what should be returned when the class object is represented as a string.

This is used to return a string representation of the object.

This function basically controls the behavior of the object if the user tries to print it as a whole.

class Person:
    def __init__(myObject, name, age):
        myObject.name = name
        myObject.age = age
    
    def say_hello(myObject):
        print("Hello, my name is", myObject.name, "and my age is", myObject.age)

person1 = Person("Alice", 25)
print(person1)

Output

__main__.Person object

Using the __str__() function, you can decide, what should be printed if the user tries to print the object.

Let’s see how this works.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print("Hello, my name is", self.name, "and my age is", self.age)
    
    def __str__(self):
        return f"Name: {self.name} \nAge: {self.age}"

person1 = Person("Alice", 25)
print(person1)

Output

Name: Alice
Age: 25

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x