Нужно найти другие решения задачи.

Bruce Jonson

Новичок
Пользователь
Окт 16, 2020
1
0
1
возможные иные решения в етих задачах?

class Concert:
"""
Make class, which has max_visitors_num attribute and its instances will have visitors_count attribute.
In case of setting visitors_count - max_visitors_num should be checked,
if visitors_count value is bigger than max_visitors_num - visitors_count should be assigned with max_visitors_num.
Example:
Concert.max_visitor_num = 50
concert = Concert()
concert.visitors_count = 1000
print(concert.visitors_count) # 50
"""
max_visitors_num = 0

class Value:
def __init__(self):
self.value = None

@staticmethod
def _new_value(value):
if value > Concert.max_visitors_num:
return Concert.max_visitors_num
else:
return value

def __get__(self, instance, owner):
return self.value

def __set__(self, instance, value):
self.value = self._new_value(value)

visitors_count = Value()


@dataclasses.dataclass()
class BookDataclass:
"""
Create dataclass with 3 fields - title (str), author (str), pages_num (int)
"""
title: str
author: str
pages_num: int


class Book:
"""
Create regular class taking 3 params on init - title, author, pages_num
Make its str() representation the same as for BookDataclass defined above.
"""

def __init__(self, title, author, pages_num):
self.author = author
self.title = title
self.pages_num = pages_num

def __str__(self):
return str(BookDataclass(title=self.title, author=self.author, pages_num=self.pages_num))
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Код вставляйте с помощью ... -> код -> python.
возможные иные решения в етих задачах?
Да. Вот, например, вариант решения первой задачи:
Python:
class Concert:
    max_visitors_num = 0

    def __init__(self):
        self._visitors_count = 0

    @property
    def visitors_count(self):
        return self._visitors_count

    @visitors_count.setter
    def visitors_count(self, value):
        if value <= self.max_visitors_num:
            self._visitors_count = value
        else:
            self._visitors_count = self.max_visitors_num


Concert.max_visitors_num = 50
concert = Concert()
concert.visitors_count = 1000
print(concert.visitors_count)  # 50
 

Форум IT Специалистов