Наследование классов не работает при создании настраиваемого класса Dimension с родительским классом int в Python 3.6 [duplicate]

Как вы отфильтровываете «свободу», кроме как с такими критериями, как «наследие», «ulic» и т. д.

   df_Fixed[~df_Fixed["Busler Group"].map(lambda x: x.startswith('Liberty'))]
34
задан me_and 13 July 2010 в 16:00
поделиться

2 ответа

int является неизменяемым, поэтому вы не можете его модифицировать после его создания, используйте __new__ вместо

class TestClass(int):
    def __new__(cls, *args, **kwargs):
        return  super(TestClass, cls).__new__(cls, 5)

print TestClass()
56
ответ дан Anurag Uniyal 20 August 2018 в 15:50
поделиться

Хотя правильные текущие ответы потенциально не завершены.

eg

a = TestClass()
b = a - 5
print type(b)

Показать b как целое число, где вы можете захотеть, чтобы это был TestClass.

Вот улучшенный ответ

class positive(int):
    def __new__(cls, value, *args, **kwargs):
        if value < 0:
            raise ValueError, "positive types must not be less than zero"
        return  super(positive, cls).__new__(cls, value)

    def __add__(self, other):
        res = super(positive, self).__add__(other)
        return self.__class__(max(res, 0))

    def __sub__(self, other):
        res = super(positive, self).__sub__(other)
        return self.__class__(max(res, 0))

    def __mul__(self, other):
        res = super(positive, self).__mul__(other)
        return self.__class__(max(res, 0))

    def __div__(self, other):
        res = super(positive, self).__div__(other)
        return self.__class__(max(res, 0))

Теперь тот же самый тип теста

a = positive(10)
b = a - 9
print type(b)

будет печатать «положительный»

4
ответ дан Jason Morgan 20 August 2018 в 15:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: