#19 Python Classes and Objects / Python Lessons for Beginners

by Alex
#19 Python Classes and Objects / Python Lessons for Beginners

Previous lesson: Arrays Python is an object-oriented programming language. Almost everything in Python is an object with its properties and methods. A class is like an object constructor or ”project” for creating objects.

Creating a Class

In order to create a class, use the class keyword. Let’s create a class with the name MyClass and the property x:

class MyClass:
x = 5

Creating an object

Now we can use a class called myClass to create objects. Let’s create an object named p1, and display the value of x:

p1 = MyClass()
print(p1.x)

Output:

5

The init function

The above examples are classes and objects in their simplest form and are not very useful in applications. To understand the meaning of classes, we need to understand the built-in __init__ function. All classes have a function called __init__() that is always executed when an object is created. Use __init__() to add values to object properties or other operations that need to be performed when creating an object. To create a class called Person, use the __init__() function to add values for name and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Vasily", 36)
print(p1.name)
print(p1.age)

Output:

Vasiliy
36

Note: The __init__() function is automatically called each time a class is used to create a new object.

Object Methods

Objects also contain methods. Methods in objects are functions that belong to the object. Let’s create a method in the Person class. Let’s add a function that displays a greeting and execute it:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hi, my name is " + self.name)
p1 = Person("Vasily", 36)
p1.myfunc()

Output:

Hi, my name is Vasily

The self parameter

The self parameter is a reference to the class itself and is used to access variables belonging to the class. It doesn’t have to be called self, you can call it whatever you want, but it must be the first parameter of any function in the class. Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hi, my name is " + abc.name)
p1 = Person("Vasily", 36)
p1.myfunc()

Conclusion:

Hi, my name is Vasily

Changing object properties

You can change object properties as follows. Let’s change the age from p1 to 40:

p1.age = 40

More examples of using classes in Python 3: Examples of working with classes in Python

Delete object properties

Object properties can be deleted using the delkeyword

del p1.age

Deleting objects

You can delete objects using the del keyword.

del p1

Related Posts

LEAVE A COMMENT