Загрузка данных
Сейчас всё выведу. Это будет длинное сообщение — 44 блока.
---
**Документ 1, Блок 1 — Простейший класс с pass**
```python
class Person:
pass
```
---
**Документ 1, Блок 2 — Создание двух объектов**
```python
class Person:
pass
tom = Person()
bob = Person()
```
---
**Документ 1, Блок 3 — Конструктор __init__**
```python
class Person:
def __init__(self):
print("Создание объекта Person")
tom = Person()
```
---
**Документ 1, Блок 4 — Атрибуты объекта**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
tom = Person("Tom", 22)
print(tom.name) # Tom
print(tom.age) # 22
tom.age = 37
print(tom.age) # 37
```
---
**Документ 1, Блок 5 — Два объекта с разными атрибутами**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
tom = Person("Tom", 22)
bob = Person("Bob", 43)
print(tom.name) # Tom
print(bob.name) # Bob
```
---
**Документ 1, Блок 6 — Динамически добавленный атрибут**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
tom = Person("Tom", 22)
tom.company = "Microsoft"
print(tom.company) # Microsoft
```
---
**Документ 1, Блок 7 — Метод say_hello**
```python
class Person:
def say_hello(self):
print("Hello")
tom = Person()
tom.say_hello() # Hello
```
---
**Документ 1, Блок 8 — Метод с параметром**
```python
class Person:
def say(self, message):
print(message)
tom = Person()
tom.say("Hello METANIT.COM")
```
---
**Документ 1, Блок 9 — Метод display_info**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name} Age: {self.age}")
tom = Person("Tom", 22)
tom.display_info() # Name: Tom Age: 22
bob = Person("Bob", 43)
bob.display_info() # Name: Bob Age: 43
```
---
**Документ 1, Блок 10 — Деструктор __del__ простой**
```python
class Person:
def __init__(self, name):
self.name = name
print("Создан человек с именем", self.name)
def __del__(self):
print("Удален человек с именем", self.name)
tom = Person("Tom")
```
---
**Документ 1, Блок 11 — Деструктор при выходе из функции**
```python
class Person:
def __init__(self, name):
self.name = name
print("Создан человек с именем", self.name)
def __del__(self):
print("Удален человек с именем", self.name)
def create_person():
tom = Person("Tom")
create_person()
print("Конец программы")
```
---
**Документ 2, Блок 1 — Публичные атрибуты (проблема)**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_person(self):
print(f"Имя: {self.name}\tВозраст: {self.age}")
tom = Person("Tom", 39)
tom.name = "Человек-паук"
tom.age = -129
tom.print_person() # Имя: Человек-паук Возраст: -129
```
---
**Документ 2, Блок 2 — Приватные атрибуты __name, __age**
```python
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def print_person(self):
print(f"Имя: {self.__name}\tВозраст: {self.__age}")
tom = Person("Tom", 39)
tom.__name = "Человек-паук"
tom.__age = -129
tom.print_person() # Имя: Tom Возраст: 39
```
---
**Документ 2, Блок 3 — Доступ через _Person__name**
```python
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def print_person(self):
print(f"Имя: {self.__name}\tВозраст: {self.__age}")
tom = Person("Tom", 39)
tom._Person__name = "Человек-паук"
tom.print_person() # Имя: Человек-паук Возраст: 39
```
---
**Документ 2, Блок 4 — Геттеры и сеттеры**
```python
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def set_age(self, age):
if 0 < age < 110:
self.__age = age
else:
print("Недопустимый возраст")
def get_age(self):
return self.__age
def get_name(self):
return self.__name
def print_person(self):
print(f"Имя: {self.__name}\tВозраст: {self.__age}")
tom = Person("Tom", 39)
tom.print_person() # Имя: Tom Возраст: 39
tom.set_age(-3486) # Недопустимый возраст
tom.set_age(25)
tom.print_person() # Имя: Tom Возраст: 25
```
---
**Документ 2, Блок 5 — Свойства через @property и @setter**
```python
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if 0 < age < 110:
self.__age = age
else:
print("Недопустимый возраст")
@property
def name(self):
return self.__name
def print_person(self):
print(f"Имя: {self.__name}\tВозраст: {self.__age}")
tom = Person("Tom", 39)
tom.print_person() # Имя: Tom Возраст: 39
tom.age = -3486 # Недопустимый возраст
print(tom.age) # 39
tom.age = 25
tom.print_person() # Имя: Tom Возраст: 25
```
---
**Документ 3, Блок 1 — Простое наследование Employee от Person**
```python
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
def display_info(self):
print(f"Name: {self.__name}")
class Employee(Person):
def work(self):
print(f"{self.name} works")
tom = Employee("Tom")
print(tom.name) # Tom
tom.display_info() # Name: Tom
tom.work() # Tom works
```
---
**Документ 3, Блок 2 — Множественное наследование (простые классы)**
```python
class Employee:
def work(self):
print("Employee works")
class Student:
def study(self):
print("Student studies")
class WorkingStudent(Employee, Student):
pass
tom = WorkingStudent()
tom.work() # Employee works
tom.study() # Student studies
```
---
**Документ 3, Блок 3 — Множественное наследование с атрибутами**
```python
class Employee:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
def work(self):
print(f"{self.name} works")
class Student:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
def study(self):
print(f"{self.name} studies")
class WorkingStudent(Employee, Student):
pass
tom = WorkingStudent("Tom")
tom.work() # Tom works
tom.study() # Tom studies
```
---
**Документ 3, Блок 4 — Конфликт методов и MRO**
```python
class Employee:
def do(self):
print("Employee works")
class Student:
def do(self):
print("Student studies")
class WorkingStudent(Employee, Student):
pass
tom = WorkingStudent()
tom.do() # Employee works
print(WorkingStudent.__mro__)
print(WorkingStudent.mro())
```
---
**Документ 4, Блок 1 — Переопределение конструктора и метода через super()**
```python
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
def display_info(self):
print(f"Name: {self.__name}")
class Employee(Person):
def __init__(self, name, company):
super().__init__(name)
self.company = company
def display_info(self):
super().display_info()
print(f"Company: {self.company}")
def work(self):
print(f"{self.name} works")
tom = Employee("Tom", "Microsoft")
tom.display_info()
# Name: Tom
# Company: Microsoft
```
---
**Документ 4, Блок 2 — Проверка типа через isinstance()**
```python
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
def do_nothing(self):
print(f"{self.name} does nothing")
class Employee(Person):
def work(self):
print(f"{self.name} works")
class Student(Person):
def study(self):
print(f"{self.name} studies")
def act(person):
if isinstance(person, Student):
person.study()
elif isinstance(person, Employee):
person.work()
elif isinstance(person, Person):
person.do_nothing()
tom = Employee("Tom")
bob = Student("Bob")
sam = Person("Sam")
act(tom) # Tom works
act(bob) # Bob studies
act(sam) # Sam does nothing
```
---
**Документ 5, Блок 1 — Атрибуты класса: type и description**
```python
class Person:
type = "Person"
description = "Describes a person"
print(Person.type) # Person
print(Person.description) # Describes a person
Person.type = "Class Person"
print(Person.type) # Class Person
```
---
**Документ 5, Блок 2 — Атрибут класса общий для всех объектов**
```python
class Person:
type = "Person"
def __init__(self, name):
self.name = name
tom = Person("Tom")
bob = Person("Bob")
print(tom.type) # Person
print(bob.type) # Person
Person.type = "Class Person"
print(tom.type) # Class Person
print(bob.type) # Class Person
```
---
**Документ 5, Блок 3 — Атрибут default_name**
```python
class Person:
default_name = "Undefined"
def __init__(self, name):
if name:
self.name = name
else:
self.name = Person.default_name
tom = Person("Tom")
bob = Person("")
print(tom.name) # Tom
print(bob.name) # Undefined
```
---
**Документ 5, Блок 4 — Совпадение атрибута класса и объекта**
```python
class Person:
name = "Undefined"
def print_name(self):
print(self.name)
tom = Person()
bob = Person()
tom.print_name() # Undefined
bob.print_name() # Undefined
bob.name = "Bob"
bob.print_name() # Bob
tom.print_name() # Undefined
Person.name = "Some Person"
bob.name = "Bob"
bob.print_name() # Bob
tom.print_name() # Some Person
```
---
**Документ 5, Блок 5 — Статический метод @staticmethod**
```python
class Person:
__type = "Person"
@staticmethod
def print_type():
print(Person.__type)
Person.print_type() # Person
tom = Person()
tom.print_type() # Person
```
---
**Документ 6, Блок 1 — Вывод объекта без __str__**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name} Age: {self.age}")
tom = Person("Tom", 23)
print(tom) # <__main__.Person object at 0x...>
```
---
**Документ 6, Блок 2 — Переопределение __str__**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(self)
def __str__(self):
return f"Name: {self.name} Age: {self.age}"
tom = Person("Tom", 23)
print(tom) # Name: Tom Age: 23
tom.display_info() # Name: Tom Age: 23
```
---
**Документ 7, Блок 1 — Оператор сложения: Counter + Counter**
```python
class Counter:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Counter(self.value + other.value)
counter1 = Counter(5)
counter2 = Counter(15)
counter3 = counter1 + counter2
print(counter3.value) # 20
```
---
**Документ 7, Блок 2 — Оператор сложения: Counter + число**
```python
class Counter:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Counter(self.value + other)
counter1 = Counter(5)
counter3 = counter1 + 6
print(counter3.value) # 11
```
---
**Документ 7, Блок 3 — Сложение возвращает число**
```python
class Counter:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other
counter1 = Counter(5)
result = counter1 + 7
print(result) # 12
```
---
**Документ 7, Блок 4 — __bool__ в if/else**
```python
class Counter:
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value > 0
def test(counter):
if counter: print("Counter = True")
else: print("Counter = False")
counter1 = Counter(3)
test(counter1) # Counter = True
counter2 = Counter(-3)
test(counter2) # Counter = False
```
---
**Документ 7, Блок 5 — __bool__ в цикле while**
```python
class Counter:
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value > 0
counter1 = Counter(3)
while(counter1):
print("Counter1: ", counter1.value)
counter1.value -= 1
```
---
**Документ 7, Блок 6 — Операторы сравнения __gt__ и __lt__**
```python
class Counter:
def __init__(self, value):
self.value = value
def __gt__(self, other):
return self.value > other.value
def __lt__(self, other):
return self.value < other.value
counter1 = Counter(1)
counter2 = Counter(2)
if counter1 > counter2:
print("counter1 больше чем counter2")
elif counter1 < counter2:
print("counter1 меньше чем counter2")
else:
print("counter1 и counter2 равны")
```
---
**Документ 7, Блок 7 — __getitem__: обращение по индексу**
```python
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def __getitem__(self, prop):
if prop == "name": return self.__name
elif prop == "age": return self.__age
return None
tom = Person("Tom", 39)
print("Name:", tom["name"]) # Name: Tom
print("Age:", tom["age"]) # Age: 39
print("Id:", tom["id"]) # Id: None
```
---
**Документ 7, Блок 8 — __contains__: оператор in**
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __contains__(self, prop):
if prop == "name" or prop == "age": return True
return False
tom = Person("Tom", 39)
print("name" in tom) # True
print("id" in tom) # False
```
---
**Документ 7, Блок 9 — Операторы парами ==, !=, <, >, <=, >=**
```python
class Counter:
def __init__(self, value):
self.value = value
def __eq__(self, other): return self.value == other.value
def __ne__(self, other): return not (self == other)
def __gt__(self, other): return self.value > other.value
def __le__(self, other): return not (self > other)
def __lt__(self, other): return self.value < other.value
def __ge__(self, other): return not (self < other)
c1 = Counter(1)
c2 = Counter(2)
print(c1 == c2) # False
print(c1 != c2) # True
print(c1 < c2) # True
print(c1 >= c2) # False
```
---
**Документ 8, Блок 1 — Простейший абстрактный класс**
```python
import abc
class Shape(abc.ABC):
pass
```
---
**Документ 8, Блок 2 — Абстрактный метод area()**
```python
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self): pass
```
---
**Документ 8, Блок 3 — Нельзя создать объект абстрактного класса**
```python
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self): pass
try:
shape = Shape()
print(shape)
except TypeError as e:
print("Ошибка:", e)
```
---
**Документ 8, Блок 4 — Rectangle реализует area()**
```python
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self): pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self): return self.width * self.height
rect = Rectangle(30, 50)
print("Rectangle area:", rect.area()) # Rectangle area: 1500
```
---
**Документ 8, Блок 5 — Rectangle и Circle, функция print_area**
```python
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self): pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self): return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self): return self.radius * self.radius * 3.14
def print_area(shape):
print("Area:", shape.area())
rect = Rectangle(30, 50)
circle = Circle(30)
print_area(rect) # Area: 1500
print_area(circle) # Area: 2826.0
```
---
**Документ 8, Блок 6 — Абстрактный класс с конструктором и неабстрактным методом**
```python
import abc
class Shape(abc.ABC):
def __init__(self, x, y):
self.x = x
self.y = y
@abc.abstractmethod
def area(self): pass
def print_point(self):
print("X:", self.x, "\tY:", self.y)
class Rectangle(Shape):
def __init__(self, x, y, width, height):
super().__init__(x, y)
self.width = width
self.height = height
def area(self): return self.width * self.height
rect = Rectangle(10, 20, 100, 100)
rect.print_point() # X: 10 Y: 20
```