English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Classes and Objects

In this article, you will learn about the core features of Python, Python objects, and classes. You will learn what a class is, how to create it, and how to use it in a program.

What are classes and objects in Python?

Python is an object-oriented programming language. Object-oriented program design focuses on objects, while procedural program design emphasizes functions.

An object is a collection of data (variables) and methods (functions) that act on these data. And, a class is the blueprint of the object.

We can view the class as a blueprint (prototype) of the house. It contains all the details about the floor, doors, windows, etc. Based on these descriptions, we build houses. Houses are objects.

Since many houses can be made through descriptions, we can create many objects based on the class. Objects are also called examples of the class, and the process of creating the object is calledInstantiation.

Defining a class in Python

like the function definition starts with the keyworddeflike the start, in Python, we use the keywordclassdefines aClass.

The first string is called docstring and has a brief description of the class. Although it is not mandatory, it is recommended to do so.

This is a simple class definition.

class MyNewClass:
    '''This is a documentation string. I have created a new class'''
    pass

A class creates a new localNamespace, and defines all its properties in it. Properties can be data or functions.

Among them there are some special attributes, which start with double underscores (__). For example, __doc__ gives us the documentation string of the class.

Once a class is defined, a new class object with the same name is created. This class object allows us to access different properties and instantiate new objects of the class.

class MyClass:
	"This is my second class"
	a = 10
	def func(self):
		print('Hello')
# Output: 10
print(MyClass.a)
# Output: <function MyClass.func at 0x0000000003079BF8>
print(MyClass.func)
# Output: 'This is my second class'
print(MyClass.__doc__)

When the program is run, the output is:

10
<function 0x7feaa932eae8="" at="" myclass.func=""
"This is my second class"

Creating an object with Python

We have seen that class objects can be used to access different properties.

It can also be used to create a new object example of the class ( instantiation ). The process of creating an object is similar toFunctionCall.

>>> ob = MyClass()

This will create a new example object ob. We can access the properties of the object using the object name prefix.

Attributes can be data or methods. The methods of an object are the corresponding functions of the class. Any function object that is a class attribute defines a method for the class's object.

This means that since MyClass.func is a function object (a class attribute), ob.func will become a method object.

class MyClass:
	"This is my second class"
	a = 10
	def func(self):
		print('Hello')
# Create a new MyClass
ob = MyClass()
# Output: <function MyClass.func at 0x000000000335B0D0>
print(MyClass.func)
# Output: <bound method MyClass.func of <__main__.MyClass object at 0x000000000332DEF0>>
print(ob.func)
# Calling function func()
# Output: Hello
ob.func()

You may have noticed the self parameter in the function definition inside the class, but we just call this method by the abbreviated name ob.func(), without anyParameters. It still works.

This is because, as long as the object calls its method, the object itself is passed as the first parameter. Therefore, ob.func() is automatically converted to MyClass.func(ob).

Generally, calling a method with a list of n parameters is equivalent to calling a function with a list of parameters created by inserting the object of the method before the first parameter.

For these reasons, the first parameter of the function in the class must be the object itself. This is usually calledself. You can use other names, but we strongly recommend that you follow the conventions.

Now, you must be familiar with class objects, instance objects, function objects, method objects, and their differences.

Constructor in Python

Functions that start with double underscores (__ ) are called special functions because they have special meanings.

__init__() function is particularly useful. It is called every time a new object of the class is instantiated.

This type of function in object-oriented programming (OOP) is also called a constructor. We usually use it to initialize all variables.

class ComplexNumber:
    def __init__(self, r = 0, i = 0):
        self.real = r
        self.imag = i
    def getData(self):
        print("{0"+{1}}.format(self.real, self.imag))
# Create another ComplexNumber object
c1 = ComplexNumber(2,3)
# Call the getData() function
# Output: 2+3j
c1.getData()
# Create another ComplexNumber object
# And create a new attribute 'attr'
c2 = ComplexNumber(5)
c2.attr = 10
# Output: (5, 0, 10)
print((c2.real, c2.imag, c2.attr))
# But c1The object has no attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
c1.attr

In the above example, we defined a new class to represent complex numbers. It has two functions, __init__() to initialize variables (default to zero), and getData() to display numbers correctly.

One interesting thing to note in the above steps is that object attributes can be dynamically created. We created an attribute for object c2A new attribute attr was created and read, but this did not create an attribute for object c1Create the attribute.

Delete attributes and objects

You can use the del statement to delete any attribute of an object at any time. Try the following operation on the Python Shell to view the output.

>>> c1 = ComplexNumber(2,3)
>>> del c1.imag
>>> c1.getData()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag'
>>> del ComplexNumber.getData
>>> c1.getData()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'getData'

We can even use the del statement to delete the object itself.

>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c' is not defined1'is not defined

In fact, it is more complex. After completion, a new example object c will be created in memory1 = ComplexNumber(1,3) namec1bound to it.

Command del c1, it will delete this binding and remove the name from the corresponding namespacec1However, the object continues to exist in memory, and if there are no other name bindings, the object will be automatically destroyed later.

This automatic destruction of unrefereed objects in Python is also known as garbage collection.