Написать класс с использованием ООП python

Рейтинг: -1Ответов: 2Опубликовано: 02.05.2023

Необходимо написать класс MiniController, в котором будут атрибуты chanel и volume, а также три метода:

  • ch_plus() - увеличивает кол-во каналов на один по кругу от 1 до 5. После пятого опять идёт первый канал.
  • vol_plus() - увеличивает громкость по +1 полосе до 30 полосок (это максимальный уровень звука)
  • vol_minus() - уменьшает уровень звука по -1 полосе до 0 полос. Телевизор всегда включается на 1 канале с уровнем звука 10.

Мое решение:

class MiniController:
    def __init__(self):
        self.chanel = 1
        self.volume = "||||||||||"
    def ch_plus(self):
        self.chanel += 1
    def vol_plus(self):
        self.volume + "|"
    def vol_minus(self):
        self.volume = self.volume[:-1]
    
pult = MiniController()
for _ in range(3):
    pult.ch_plus()
print(pult.chanel)
for _ in range(15):
    pult.ch_plus()
print(pult.chanel)
for _ in range(50):
    pult.vol_plus()
print(pult.volume)
pult.vol_minus()
print(pult.volume)

Не могу сделать ch_plus(), чтобы кол-во каналов увеличивалось на один по кругу от 1 до 5. После пятого опять идёт первый и vol_plus() увеличивает громкость по +1 полосе до 30 полосок (это максимальный уровень звука) и vol_minus() - уменьшает уровень звука по -1 полосе до 0 полос. После запуска должно быть:

4
4
||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||

В моем решении не так. Как исправить и сделать правильно?

Ответы

▲ 0
from itertools import cycle

class MiniController:
    def __init__(self):
        self._c = cycle(range(1, 6))
        self.chanel = next(self._c)
        self._v = 10

    def ch_plus(self):
        self.chanel = next(self._c)
    def vol_plus(self):
        self._v = min(self._v + 1, 30)
    def vol_minus(self):
        self._v = max(self._v - 1, 0)

    @property
    def volume(self):
        return '|' * self._v


pult = MiniController()
for _ in range(3):
    pult.ch_plus()
print(pult.chanel)
for _ in range(15):
    pult.ch_plus()
print(pult.chanel)
for _ in range(50):
    pult.vol_plus()
print(pult.volume)
pult.vol_minus()
print(pult.volume)

4
4
||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||
▲ 0
Вроде так тоже работает:
class MiniController:
    def __init__(self):
        self.chanel = 1
        self.volume = "||||||||||"
    def ch_plus(self):
        if self.chanel == 5:
            self.chanel = 1
        elif self.chanel != 5:
            self.chanel += 1
    def vol_plus(self):
        if 10 <= len(self.volume) < 30:
            self.volume = self.volume + "|"
    def vol_minus(self):
        if len(self.volume) == 30:
            self.volume = self.volume[:-1]