Python Intermediate Series: Python Objects

2018-10-14
Image of icons showing different Objects in Python

Python is one of the most widely-used programming languages today since it is an object-oriented language with a variety of applications.


What are Objects?

Anything in Python is an object. Objects in Python are much like every other object-oriented language: they consist of properties and methods. In Python, we use a class to construct an object.


To create a class in Python, we use the standard keyword, “class.” For example:

Class student:

age = 10


Now we can use this class to create student objects in Python. Let us begin by creating a student object named John and printing the value of age:

John = student()

print(John.age)


The value of the printed output will be 10.


You Must Initialize

All classes in Python have a built in function called __init__(). This function is used to assign values to the object’s properties when the class is initialized.


Next, we will cover an access keyword called “self.” Self can be much like the “this” keyword in the famous C++ language.

What is Self?

Self is a like a pointer to the class itself. As a result, it is used to access and modify the variables from within the class. If you don’t like the phrase “self,” you can rename the keyword itself to whatever you like. Just remember to put the new name as the first parameter of any function inside that class.


For example:

Class student:

def __init__(self, name, age):

self.name = name

self.age = age[EG1]

s1 = student("John", "10)


Methods:

Objects also contain methods. Methods are functions that are implemented inside the object, and that can be called from inside or outside the object.


For example:

Class student:

def __init__(self, name, age):

self.name = name

self.age = age

def introduce(self):

print("my name is " + self.name)


s1 = Person("John", 10)

s1.introduce()


If we want to delete a property from the object, we can use the del() method. For example:

del s1.age


If you want to exercise what you have learned, start practicing with RoboGarden now. Register for free.


Python Series Intermediate python

RELATED BLOGS

Start Python coding

Let's start python coding with RoboGarden learning journey.

Canada Flag Privacy Policy Terms of Use
Got an invite