AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Python: Creating Classes and Objects

PARTAGEZ

Python classes are like construction plans or templates. They allow you to write reusable code in the form of class attributes and methods.

Python Class: What is it?

A class is a abstract concept which defines the attributes and methods an object can have. Python classes serve as a template for creating concrete objects that are instances of that class. For example, a class might be called voiturewhich has attributes such as color and brand, as well as methods conduire__ Or freiner__.

Each object of a class can have its own values ​​for attributes, but shares basic methods and behavioral framework with other instances of the same class. For example, an object ma_voiture of style voiture can be created with color __Rouge__ and the brand __Toyota__and the methods conduire__ Or freiner__ of the class will be automatically transferred to the instance.

Creating Python Classes

In Python, you define classes using the keyword class.

class MyClass:
    # Constructor method called when creating an object
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2
    # Method defined within the class
    def my_method(self):
        return f"Attribute 1: {self.attribute1}, Attribute 2: {self.attribute2}"

python

In this Python code, we create a class called MyClass. This one has a builder __init__ which is called when an object is created and initializes two attributes, attribute1 And attribute2. The method my_method returns a formatted string that contains the values ​​of these attributes.

To derive an object from this class, use the class name followed by parentheses:

object1 = MyClass("Value 1", "Value 2")
result = object1.my_method()

python

Web hosting with personal advisor!

Powerful, flexible and high-performance web hosting with email box, personal advisor and domain included 1time year !

Domain

SSL Certificate

24/7 Support

Examples of using Python classes

Python classes can create complex systems and relationships between different entities. Below we present some possibilities for working with Python classes.

Function __str()__

Function __str__() Python's method is a special method that you can define in Python classes. When implemented, it returns a string that represents a user-friendly representation of an object. You can apply the function str() directly to the object or combine it with an instruction print().

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}"
person1 = Person("Alice", 30)
print(person1) # Output: Name: Alice, Age: 30

python

In our code, the method __str__() created in the class Person a formatted string containing a person's name and age. When print(person1) is executed, it automatically calls the method __str__() of the object person1 and displays the string returned by this method.

Defining Methods in Python Classes

In Python you have the ability to define methods within a class to perform operations on objects of this class. These methods can then be called by the created objects.

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
     
    def area(self):
        return self.length * self.width
    def perimeter(self):
        return 2 * (self.length + self.width)
# Creating an object of the class
my_rectangle = Rectangle(5, 10)
# Calling methods of the object
area = my_rectangle.area()
perimeter = my_rectangle.perimeter()
# Printing the calculated values
print("Area =", area) # Output: Area = 50
print("Perimeter =", perimeter) # Output: Perimeter = 30

python

In this Python example, we create the class Rectanglewhich includes both methods area() And perimeter(). These are used to calculate the area and perimeter of a rectangle, based on the length and width values ​​passed when initializing the object. In Python, self in a class method represents a reference to the current object on which the method is applied.

The object my_rectangle is created with a length of 5 and a width of 10. Then we call the methods area() And perimeter() on this object to calculate the corresponding values.

Edit object properties

The point operator . can be used to access the object specific attributes and update their values. It is possible to directly assign new values ​​to the attribute.

person1.name = "Sarah"
person1.age = 35

python

The keyword del is used to remove properties from an object.

Note

You should take into account that instance variables are different from Python Class Variables. Class variables are defined outside the constructor and can only be modified using the class name.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact