py objects Flashcards

(22 cards)

1
Q

Class Definition and Object Instantiation
In Python, a class serves as a blueprint for constructing user-defined objects. It encapsulates both data (attributes) and behaviours (methods), supporting modular and reusable code. The class keyword is used to declare a new class, which defines a new object type. Each time this class is instantiated, an independent object (or instance) is created. This mechanism allows for the definition of multiple discrete instances with potentially unique states, although they may share common behaviour and data through class-level attributes.

A

Определение классов и создание объектов
В Python класс представляет собой шаблон (или чертёж) для создания пользовательских объектов. Он инкапсулирует как данные (атрибуты), так и поведение (методы), обеспечивая модульность и повторное использование кода. Ключевое слово class используется для объявления нового класса, определяющего новый тип объектов. При каждом создании экземпляра этого класса создаётся независимый объект, обладающий собственным состоянием. Это позволяет определять множество уникальных экземпляров, разделяющих общее поведение и/или данные.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Определение классов и создание объектов
В Python класс представляет собой шаблон (или чертёж) для создания пользовательских объектов. Он инкапсулирует как данные (атрибуты), так и поведение (методы), обеспечивая модульность и повторное использование кода. Ключевое слово class используется для объявления нового класса, определяющего новый тип объектов. При каждом создании экземпляра этого класса создаётся независимый объект, обладающий собственным состоянием. Это позволяет определять множество уникальных экземпляров, разделяющих общее поведение и/или данные.

A

Class Definition and Object Instantiation
In Python, a class serves as a blueprint for constructing user-defined objects. It encapsulates both data (attributes) and behaviours (methods), supporting modular and reusable code. The class keyword is used to declare a new class, which defines a new object type. Each time this class is instantiated, an independent object (or instance) is created. This mechanism allows for the definition of multiple discrete instances with potentially unique states, although they may share common behaviour and data through class-level attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Attributes and the Dot Operator
Attributes in Python classes are variables that store state or data. These are classified into class attributes and instance attributes, depending on their scope and declaration. Class attributes are declared directly within the class body and are shared across all instances. They can be accessed via the dot operator using either the class name or an instance reference. For example, Dog.sound or dog1.sound both refer to the same attribute if sound is defined at the class level. Instance attributes, by contrast, are typically defined in the constructor and are unique to each object.

A

Атрибуты и оператор точки
Атрибуты в классах Python — это переменные, представляющие состояние объекта. Их можно разделить на атрибуты класса и атрибуты экземпляра, в зависимости от области видимости. Атрибуты класса объявляются внутри тела класса и доступны всем экземплярам. Их можно получить с помощью оператора точки как через имя класса (Dog.sound), так и через экземпляр (dog1.sound). Атрибуты экземпляра, напротив, обычно определяются в конструкторе и уникальны для каждого объекта.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Атрибуты и оператор точки
Атрибуты в классах Python — это переменные, представляющие состояние объекта. Их можно разделить на атрибуты класса и атрибуты экземпляра, в зависимости от области видимости. Атрибуты класса объявляются внутри тела класса и доступны всем экземплярам. Их можно получить с помощью оператора точки как через имя класса (Dog.sound), так и через экземпляр (dog1.sound). Атрибуты экземпляра, напротив, обычно определяются в конструкторе и уникальны для каждого объекта.

A

Attributes and the Dot Operator
Attributes in Python classes are variables that store state or data. These are classified into class attributes and instance attributes, depending on their scope and declaration. Class attributes are declared directly within the class body and are shared across all instances. They can be accessed via the dot operator using either the class name or an instance reference. For example, Dog.sound or dog1.sound both refer to the same attribute if sound is defined at the class level. Instance attributes, by contrast, are typically defined in the constructor and are unique to each object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Initialisation via __init__ Constructor
The __init__() method in Python serves as the constructor and is invoked automatically upon object instantiation. It enables initialisation of instance-specific state by assigning values to attributes. This method must accept self as its first parameter, which is a reference to the object being created. Attributes assigned via self.attribute_name become instance variables. For example, self.name = name binds the provided argument name to the instance’s internal state. This facilitates parameterised instantiation of objects with distinct data.

A

Инициализация через конструктор __init__
Метод __init__() в Python — это конструктор, автоматически вызываемый при создании объекта. Он позволяет инициализировать состояние конкретного экземпляра, присваивая значения его атрибутам. Метод обязательно принимает первым параметром self, который указывает на создаваемый объект. Атрибуты, задаваемые через self.attribute_name, становятся переменными экземпляра. Например, self.name = name связывает переданный аргумент name с внутренним состоянием объекта.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Инициализация через конструктор __init__
Метод __init__() в Python — это конструктор, автоматически вызываемый при создании объекта. Он позволяет инициализировать состояние конкретного экземпляра, присваивая значения его атрибутам. Метод обязательно принимает первым параметром self, который указывает на создаваемый объект. Атрибуты, задаваемые через self.attribute_name, становятся переменными экземпляра. Например, self.name = name связывает переданный аргумент name с внутренним состоянием объекта.

A

Initialisation via __init__ Constructor
The __init__() method in Python serves as the constructor and is invoked automatically upon object instantiation. It enables initialisation of instance-specific state by assigning values to attributes. This method must accept self as its first parameter, which is a reference to the object being created. Attributes assigned via self.attribute_name become instance variables. For example, self.name = name binds the provided argument name to the instance’s internal state. This facilitates parameterised instantiation of objects with distinct data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Demonstrating Constructor Functionality
Consider the following:

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Here, species is a class-level attribute common to all dogs, while name and age are per-instance values. Upon creating an object with dog1 = Dog(“Buddy”, 3), the values “Buddy” and 3 are bound to dog1 via the constructor. This approach ensures encapsulated object configuration during instantiation.

A

Демонстрация работы конструктора
Рассмотрим пример:

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Здесь species — это общий для всех экземпляров атрибут класса, тогда как name и age — индивидуальные данные для каждого объекта. При создании dog1 = Dog(“Buddy”, 3), аргументы “Buddy” и 3 сохраняются в соответствующих атрибутах. Такой подход обеспечивает конфигурацию объекта уже на этапе его создания.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Демонстрация работы конструктора
Рассмотрим пример:

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Здесь species — это общий для всех экземпляров атрибут класса, тогда как name и age — индивидуальные данные для каждого объекта. При создании dog1 = Dog(“Buddy”, 3), аргументы “Buddy” и 3 сохраняются в соответствующих атрибутах. Такой подход обеспечивает конфигурацию объекта уже на этапе его создания.

A

Demonstrating Constructor Functionality
Consider the following:

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Here, species is a class-level attribute common to all dogs, while name and age are per-instance values. Upon creating an object with dog1 = Dog(“Buddy”, 3), the values “Buddy” and 3 are bound to dog1 via the constructor. This approach ensures encapsulated object configuration during instantiation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Role of self in Method Definitions
The self parameter is a mandatory first argument in instance methods and allows the object to access its own attributes and invoke other methods. It acts as a reference to the invoking object. For instance:

def bark(self):
    print(f"{self.name} is barking!”)

When calling dog1.bark(), Python implicitly passes dog1 as the value of self. This ensures that method calls operate on the correct instance-specific state.

A

Роль self в методах экземпляра
Параметр self обязателен в методах экземпляра и предоставляет доступ к атрибутам и другим методам конкретного объекта. Это ссылка на тот экземпляр, который вызывает метод. Например:

def bark(self):
    print(f"{self.name} is barking!”)

При вызове dog1.bark() Python неявно передаёт dog1 в качестве self, обеспечивая корректную работу с состоянием именно этого экземпляра.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Роль self в методах экземпляра
Параметр self обязателен в методах экземпляра и предоставляет доступ к атрибутам и другим методам конкретного объекта. Это ссылка на тот экземпляр, который вызывает метод. Например:

def bark(self):
    print(f"{self.name} is barking!”)

При вызове dog1.bark() Python неявно передаёт dog1 в качестве self, обеспечивая корректную работу с состоянием именно этого экземпляра.

A

Role of self in Method Definitions
The self parameter is a mandatory first argument in instance methods and allows the object to access its own attributes and invoke other methods. It acts as a reference to the invoking object. For instance:

def bark(self):
    print(f"{self.name} is barking!”)

When calling dog1.bark(), Python implicitly passes dog1 as the value of self. This ensures that method calls operate on the correct instance-specific state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Overriding Default String Representation with __str__
Python allows classes to define a human-readable string representation of their instances via the __str__() method. Without overriding, calling print(obj) yields an uninformative memory address. By implementing:

def \_\_str\_\_(self):
    return f"{self.name} is {self.age} years old.”

we allow objects to be printed in a meaningful way. This is crucial for debugging and logging, as it provides semantic insight into an object’s state.

A

Переопределение строкового представления через __str__
Python позволяет определить человеко-читаемое строковое представление объекта с помощью метода __str__(). Без переопределения вызов print(obj) выведет что-то вроде <__main__.ClassName object at 0x00000123>. Реализация:

def \_\_str\_\_(self):
    return f"{self.name} is {self.age} years old.”

позволяет отображать объект в более информативной форме, что полезно при отладке и логировании.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Переопределение строкового представления через __str__
Python позволяет определить человеко-читаемое строковое представление объекта с помощью метода __str__(). Без переопределения вызов print(obj) выведет что-то вроде <__main__.ClassName object at 0x00000123>. Реализация:

def \_\_str\_\_(self):
    return f"{self.name} is {self.age} years old.”

позволяет отображать объект в более информативной форме, что полезно при отладке и логировании.

A

Overriding Default String Representation with __str__
Python allows classes to define a human-readable string representation of their instances via the __str__() method. Without overriding, calling print(obj) yields an uninformative memory address. By implementing:

def \_\_str\_\_(self):
    return f"{self.name} is {self.age} years old.”

we allow objects to be printed in a meaningful way. This is crucial for debugging and logging, as it provides semantic insight into an object’s state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Class Variables vs Instance Variables
Understanding the difference between class variables and instance variables is essential for effective object-oriented programming in Python. Class variables are shared among all instances and are defined in the class scope. Conversely, instance variables are bound to the object and declared inside the constructor or methods using self. Altering a class variable via the class name changes it for all instances, whereas modifying an instance variable only affects the specific object.

A

Переменные класса и экземпляра
В Python переменные, определённые внутри класса, делятся на переменные класса и переменные экземпляра. Переменные класса — это общие данные, определённые в области класса и разделяемые между всеми экземплярами. Переменные экземпляра, напротив, задаются в методах, как правило — в __init__, и уникальны для каждого объекта. Изменение переменной класса влияет на все экземпляры, а изменение переменной экземпляра касается только конкретного объекта.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Переменные класса и экземпляра
В Python переменные, определённые внутри класса, делятся на переменные класса и переменные экземпляра. Переменные класса — это общие данные, определённые в области класса и разделяемые между всеми экземплярами. Переменные экземпляра, напротив, задаются в методах, как правило — в __init__, и уникальны для каждого объекта. Изменение переменной класса влияет на все экземпляры, а изменение переменной экземпляра касается только конкретного объекта.

A

Class Variables vs Instance Variables
Understanding the difference between class variables and instance variables is essential for effective object-oriented programming in Python. Class variables are shared among all instances and are defined in the class scope. Conversely, instance variables are bound to the object and declared inside the constructor or methods using self. Altering a class variable via the class name changes it for all instances, whereas modifying an instance variable only affects the specific object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Class Variable Scope

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Here, species is shared across all Dog instances. If you execute Dog.species = “Feline”, all existing and future Dog objects will reflect this change unless they explicitly override the attribute at the instance level. However, modifying dog1.name to “Max” only affects dog1, not other instances like dog2.

A

Область действия переменных

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Атрибут species здесь — это переменная класса. Если выполнить Dog.species = “Feline”, это затронет все объекты, если только они явно не переопределяют это значение. Однако изменение dog1.name = “Max” повлияет только на объект dog1 и не затронет другие экземпляры.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Область действия переменных

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Атрибут species здесь — это переменная класса. Если выполнить Dog.species = “Feline”, это затронет все объекты, если только они явно не переопределяют это значение. Однако изменение dog1.name = “Max” повлияет только на объект dog1 и не затронет другие экземпляры.

A

Class Variable Scope

class Dog:
    species = "Canine"
    def \_\_init\_\_(self, name, age):
        self.name = name
        self.age = age

Here, species is shared across all Dog instances. If you execute Dog.species = “Feline”, all existing and future Dog objects will reflect this change unless they explicitly override the attribute at the instance level. However, modifying dog1.name to “Max” only affects dog1, not other instances like dog2.

17
Q

Object-Oriented Initialisation with Parameters
The constructor can take arguments to parameterise object creation. Consider:

class Person:
    def \_\_init\_\_(self, name):
        self.name = name

Creating p1 = Person(‘Nikhil’) binds the value ‘Nikhil’ to the name attribute of the p1 object. This allows creation of multiple unique objects via different constructor arguments. Each object has its own identity and state, determined by the parameters passed during instantiation.

A

Инициализация объектов с параметрами
Конструктор может принимать аргументы, позволяющие параметризовать создание объекта. Например:

class Person:
    def \_\_init\_\_(self, name):
        self.name = name

Создание p1 = Person(‘Nikhil’) присваивает значение ‘Nikhil’ атрибуту name объекта p1. Это позволяет создавать множество уникальных объектов, передавая разные аргументы в конструктор. Каждый объект будет иметь своё собственное состояние.

18
Q

Инициализация объектов с параметрами
Конструктор может принимать аргументы, позволяющие параметризовать создание объекта. Например:

class Person:
    def \_\_init\_\_(self, name):
        self.name = name

Создание p1 = Person(‘Nikhil’) присваивает значение ‘Nikhil’ атрибуту name объекта p1. Это позволяет создавать множество уникальных объектов, передавая разные аргументы в конструктор. Каждый объект будет иметь своё собственное состояние.

A

Object-Oriented Initialisation with Parameters
The constructor can take arguments to parameterise object creation. Consider:

class Person:
    def \_\_init\_\_(self, name):
        self.name = name

Creating p1 = Person(‘Nikhil’) binds the value ‘Nikhil’ to the name attribute of the p1 object. This allows creation of multiple unique objects via different constructor arguments. Each object has its own identity and state, determined by the parameters passed during instantiation.

19
Q

Inheritance and Constructor Chaining
Inheritance allows a class to inherit attributes and methods from a parent class. Constructors in Python must be explicitly chained using the parent class’s __init__() method. In the following:

class A:
    def \_\_init\_\_(self, something):
        print("A init called")
        self.something = something

class B(A):
    def \_\_init\_\_(self, something):
        A.\_\_init\_\_(self, something)
        print("B init called”)

Instantiation of B triggers both constructors, illustrating constructor chaining. This behaviour ensures that the base class’s attributes are properly initialised before the subclass extends or overrides them.

A

Наследование и цепочка вызова конструкторов
Наследование позволяет одному классу получать свойства и методы другого. Конструкторы в Python должны быть явно вызваны при наследовании, используя метод __init__() родительского класса. В примере:

class A:
    def \_\_init\_\_(self, something):
        print("A init called")
        self.something = something

class B(A):
    def \_\_init\_\_(self, something):
        A.\_\_init\_\_(self, something)
        print("B init called”)

Создание объекта B приведёт к вызову сначала конструктора родительского класса, а затем конструктора подкласса. Это гарантирует корректную инициализацию атрибутов базового класса.

20
Q

Наследование и цепочка вызова конструкторов
Наследование позволяет одному классу получать свойства и методы другого. Конструкторы в Python должны быть явно вызваны при наследовании, используя метод __init__() родительского класса. В примере:

class A:
    def \_\_init\_\_(self, something):
        print("A init called")
        self.something = something

class B(A):
    def \_\_init\_\_(self, something):
        A.\_\_init\_\_(self, something)
        print("B init called”)

Создание объекта B приведёт к вызову сначала конструктора родительского класса, а затем конструктора подкласса. Это гарантирует корректную инициализацию атрибутов базового класса.

A

Inheritance and Constructor Chaining
Inheritance allows a class to inherit attributes and methods from a parent class. Constructors in Python must be explicitly chained using the parent class’s __init__() method. In the following:

class A:
    def \_\_init\_\_(self, something):
        print("A init called")
        self.something = something

class B(A):
    def \_\_init\_\_(self, something):
        A.\_\_init\_\_(self, something)
        print("B init called”)

Instantiation of B triggers both constructors, illustrating constructor chaining. This behaviour ensures that the base class’s attributes are properly initialised before the subclass extends or overrides them.

21
Q

Customising Initialisation Order
Python offers flexibility in constructor invocation order. While it’s conventional to call the superclass constructor first, developers may reverse this if the subclass requires certain setup before delegating to the parent. For example:

class A:
    def \_\_init\_\_(self, something):
        print("A init called")
        self.something = something

class B(A):
    def \_\_init\_\_(self, something):
        print("B init called")
        self.something = something
        A.\_\_init\_\_(self, something)

In this variation, the subclass constructor executes its logic first, then invokes the superclass’s constructor. This level of control is useful when the subclass must perform pre-initialisation processing.

A

Пользовательский порядок вызова __init__
Python предоставляет гибкость в порядке вызова конструкторов при наследовании. Хотя по умолчанию конструктор родителя вызывается первым, можно изменить порядок вызовов. Например:

class B(A):
    def \_\_init\_\_(self, something):
        print("B init called")
        self.something = something
        A.\_\_init\_\_(self, something)

Здесь сначала выполняется логика конструктора подкласса, а затем вызывается конструктор родителя. Это может быть полезно, если необходимо предварительно подготовить состояние дочернего класса перед инициализацией родительского.

22
Q

Пользовательский порядок вызова __init__
Python предоставляет гибкость в порядке вызова конструкторов при наследовании. Хотя по умолчанию конструктор родителя вызывается первым, можно изменить порядок вызовов. Например:

python
Copy
Edit
class B(A):
def __init__(self, something):
print(“B init called”)
self.something = something
A.__init__(self, something)
Здесь сначала выполняется логика конструктора подкласса, а затем вызывается конструктор родителя. Это может быть полезно, если необходимо предварительно подготовить состояние дочернего класса перед инициализацией родительского.

A

Customising Initialisation Order
Python offers flexibility in constructor invocation order. While it’s conventional to call the superclass constructor first, developers may reverse this if the subclass requires certain setup before delegating to the parent. For example:

class A:
    def \_\_init\_\_(self, something):
        print("A init called")
        self.something = something

class B(A):
    def \_\_init\_\_(self, something):
        print("B init called")
        self.something = something
        A.\_\_init\_\_(self, something)

In this variation, the subclass constructor executes its logic first, then invokes the superclass’s constructor. This level of control is useful when the subclass must perform pre-initialisation processing.