Fundamentals of classes and objects in Python: creating user data types and work with their properties and methods.

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

What is a class in Python?

A class in Python is a template or drawing for creating objects. It defines a set of attributes (data) and methods (functions) that characterize any object of this class. Classes are the foundation of object-oriented programming (OOP) in Python and allow you to create new types of objects with common characteristics and behavior.

Syntax of the class declaration

A class is declared using the keyword class, followed by the class name. According to the PEP 8 convention, the class name must begin with a capital letter and use the camelCase style:

class ClassName:
    # Class body
    pass

Constructor of the init() class

Constructor __init__() is a special method that is automatically called when creating a new class object. It is used to initialize the attributes of an object.:

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return "Woof!"

Creating objects (instances of a class)

Objects are created by calling a class as a function. The __init__() method is automatically called.:

# Creating an object of the Dog class
my_dog = Dog("Buddy", 3)

# Access to the attributes
of the print object(my_dog.name ) # Output: Buddy
print(my_dog.age) # Output: 3

# Calling
the print object method(my_dog.bark()) # Output: Woof!

Attributes and methods of the class

Instance Attributes

Instance attributes are variables that belong to a specific class object. They are defined inside the __init__() method using the keyword self:

class Person:
    def __init__(self, name, age):
self.name = name # instance attribute
        self.age = age # instance attribute

    def say_hello(self):
return f"Hi, my name is {self.name }, I am {self.age} years old"

Instance methods

Instance methods are functions defined inside a class that work with a specific object. The first parameter is always passed self, a reference to the current object:

 

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name }, I am {self.age} years old")

    def have_birthday(self):
        self.age += 1
        print(f"Happy birthday! Now I am {self.age} years old")

# Creating an object and using methods
person1 = Person("Anna", 25)
person1.say_hello() # Conclusion: Hi, my name is Anna, I am 25 years
old person1.have_birthday() # Conclusion: Happy birthday! I'm 26 years old now.

Practical examples of using classes

Example 1: A class for representing a car

class Car:
    def __init__(self, make, model, year, mileage=0):
        self.make = make
        self.model = model
        self.year = year
        self.mileage = mileage
        self.is_running = False

    def start_engine(self):
        if not self.is_running:
            self.is_running = True
            return f"{self.make} {self.model} started"
return "Engine is already running"

    def stop_engine(self):
        if self.is_running:
            self.is_running = False
            return f"{self.make} {self.model} turned off"
return "Engine already turned off"

    def drive(self, distance):
        if self.is_running:
            self.mileage += distance
            return f"We drove {distance} km. Total mileage: {self.mileage} km"
        return "Start the engine first"

    def display_info(self):
        status = "running" if self.is_running else "disabled"
return f"{self.year} {self.make} {self.model} (mileage: {self.mileage} km, engine {status})"

# Creating and using objects
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Civic", 2019, 15000)

print(car1.display_info()) # 2020 Toyota Camry (mileage: 0 km, engine turned off)
print(car1.start_engine()) # Toyota Camry started
print(car1.drive(100)) # Drove 100 km. Total mileage: 100 km

Example 2: A class for a bank account

class BankAccount:
    def __init__(self, account_number, owner_name, initial_balance=0):
        self.account_number = account_number
        self.owner_name = owner_name
        self.balance = initial_balance

    def deposit(self, amount):
        if amount > 0:
            self.balance += amount
            return f"Replenishment in {amount} rubles. Balance: {self.balance} rub."
return "The deposit amount must be positive"

    def withdraw(self, amount):
        if amount > 0:
            if amount <= self.balance:
                self.balance -= amount
                return f"Withdrawn {amount} rub. Balance: {self.balance} rub."
return "Insufficient funds in the account"
        return "The withdrawal amount must be positive"

    def get_balance(self):
return f"Account balance {self.account_number}: {self.balance} rub."

# Using the class
account = BankAccount("123456789", "Ivan Ivanov", 1000)
print(account.get_balance()) # Account balance 123456789: 1000 rub.
print(account.deposit(500)) # Replenishment for 500 rubles. Balance: 1,500 rubles.
print(account.withdraw(200)) # 200 rubles withdrawn. Balance: 1300 rubles.

Advantages of using classes in Python

  1. Encapsulation: Data and methods are combined in one place
  2. Code reuse: One class can create many objects
  3. Modularity: Classes help to structure the code
  4. Abstraction: Complex logic is hidden behind a simple interface
  5. Inheritance: The ability to create new classes based on existing ones

Basic terms

  • The class is a template for creating objects
  • Object (instance) - a specific implementation of the class
  • Attribute is a variable belonging to the object
  • Method is a function belonging to the class
  • Constructor - method __init__() for initializing an object
  • self - reference to the current object

Classes in Python provide a powerful tool for creating structured and reusable code. They allow you to simulate real entities and their interactions, which makes programs more understandable and easier to maintain.

 

 

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base