Показать статистику
0 голосов
от (1.2тыс. баллов)

Есть такой код (тренировочный, в целях изучения языка): 

#!/usr/local/bin/python3


class Zhivotnoe:
    def __init__(legs, color, weight):
        print("Your animal has {} legs, it is {} color and it weights {} pounds".format(legs, color, weight))
        return None


def main():
    legs = input("Enter how many legs: ")
    if not legs:
        legs = None
    color = input("Enter the color: ")
    if not color:
        color = "blue"
    weight = input("Enter the weight: ")
    if not weight:
        weight = "endless because you did not provide it"

    Zhivotnoe.__init__(legs, color, weight)


if __name__ == "__main__":
    main()

Как видно из кода, при запуске будут запрошены параметры (legs, color, weight) и если ничего не введено - подставятся значения, заданные условием if.

Вопрос - как переписать код, что бы не городить if ?

462 просмотров 1 ответов

1 Ответ

0 голосов
от (17.4тыс. баллов)

Можно просто поставить в той же строке, где вводятся данные оператор "or" и указать значение по-умолчанию. 

#!/usr/local/bin/python3


class Zhivotnoe:
    def __init__(legs, color, weight):
        print("Your animal has {} legs, it is {} color and it weights {} pounds".format(legs, color, weight))
        return None


def main():
    legs = input("Enter how manby legs: ") or None
    color = input("Enter the color: ") or "blue"
    weight = input("Enter the weight: ") or "endless"

    Zhivotnoe.__init__(legs, color, weight)


if __name__ == "__main__":
    main()

На мой взгляд, это выглядит более читаемо.

от (17.4тыс. баллов)
редактировать от
0

А вообще так не годится, потому что нельзя вызывать конструктор класса. Нужно создавать объект класса. 

cat = Zhivotnoe(4, white, 10)

Получится нечто вроде: 

#!/usr/local/bin/python3


class Zhivotnoe:
    def __init__(self, legs=None, color='blue', weight='endless'):
        self.legs = legs
        self.color = color
        self.weight = weight

    def __repr__(self):
        return 'Your animal has {} legs, it is {} color and it weights {} pounds'.format(self.legs, self.color, self.weight)

def main():
    cat = Zhivotnoe(4, 'black', 3000)
    pidgin = Zhivotnoe(2, 'blue', 1000)

    print(cat)
    print(pidgin)

if _name_ == "_main_":
    main()
...