为什么断言在抽象类中不起作用?

问题描述 投票:0回答:1

我需要您的帮助来理解为什么assert在我的代码中不起作用(我正在使用此代码来学习抽象类,getter和setters,我是抽象类的新手。

如果我在power属性上放置一个负数,则代码应该以警告停止,但是assert会忽略power是负数,零还是非负数。

另一种在基类上没有具体方法的测试代码,但是在子类上具有相同的具体方法的代码停止并给我警告。

这是我要测试的完整代码。

from abc import ABC, abstractmethod

class Load(ABC):
    #That's a class to create load to circuits.
    @abstractmethod
    def __init__(self, power=0, power_factor=1):
        self.__power = power
        self.__power_factor = power_factor

    # the attributte name and the method name must be  same
    # which is used to set the value for the attributte
    @property
    def power(self):
        return self.__power

    @power.setter
    def power(self, power):
        # AT TEST SHOULD STOP HERE ANY CONDITION - ONLY TEST PURPOSEs
        # BUT HERE ASSERT IS IGNORED
        assert (power < 0), "power must be non-negative"
        assert (power >= 0), "***power must be negative - ONLY TEST"
        self.__power = power

    @property
    def power_factor(self):
        return self.__power_factor

    @power_factor.setter
    def power_factor(self, power_factor):
        assert 0 < power_factor <= 1, "power factor must be greater 0 until 1"
        self.__power_factor = power_factor


class Specific(Load):
    def __init__(self, power, power_factor):
        super().__init__(power, power_factor)
    # the attributte name and the method name must be  same
    # which is used to set the value for the attributte

### ONLY TESTs PURPOSE

a = Specific(-11,1) # TO FORCE THE ERROR
print(a.power, a.power_factor)
a.power_factor = .4
print(a.power, a.power_factor)

我在做什么错?

python class abstract assert assertion
1个回答
0
投票

您不使用您的二传手。使用

class Load(ABC):
    #That's a class to create load to circuits.
    @abstractmethod
    def __init__(self, power=0, power_factor=1):
        self.power = power
        self.__power_factor = power_factor
© www.soinside.com 2019 - 2024. All rights reserved.